为移动设备优化可视化
由于您已经为两个年份添加了标签,x 轴标题现在基本上是多余的。您现在将为图形添加国家标签,这样就可以移除所有坐标轴。
在本练习中,您将遇到一个可能对您来说是新的用法:可以为单个几何层(如 geom_text())提供新的数据集,使其不使用初始 ggplot() 调用传入的数据集。在这里,您需要这样做,因为您只想为每个箭头添加一个标签。如果使用原始数据集 ilo_data,将会添加两个标签,因为每个国家在数据集中有两条观测:一条是 1996 年,一条是 2006 年。
本练习是课程的一部分
在 Tidyverse 中用数据进行沟通
练习说明
- 我们已创建新的数据集
median_working_hours,以确保每个国家只有一个标签。使用str()查看其结构。 - 在新的
geom_text()调用中,将median_working_hours作为data参数,以为每个国家添加标签。- 为
geom_text()正确指定所需的美学映射:x和label,并指向median_working_hours数据集中相应的变量。
- 为
- 在自定义的
theme()调用中,为所有axis.和panel.grid参数指定element_blank(),以移除所有坐标轴和背景网格。 - 运行最终代码后,请在右侧调整绘图窗口大小,以模拟竖屏(窄而高)的移动设备屏幕——所有标签都将适配绘图区。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Compute temporary data set for optimal label placement
median_working_hours <- ilo_data %>%
group_by(country) %>%
summarize(median_working_hours_per_country = median(working_hours)) %>%
ungroup()
# Have a look at the structure of this data set
___
ilo_dot_plot +
# Add label for country
geom_text(data = ___,
aes(y = country,
x = ___,
label = ___),
vjust = 2,
family = "Bookman",
color = "gray25") +
# Remove axes and grids
theme(
axis.ticks = ___,
axis.title = ___,
axis.text = ___,
panel.grid = ___,
# Also, let's reduce the font size of the subtitle
plot.subtitle = element_text(size = 9)
)