為行動裝置最佳化圖表
由於你已經為兩個年份加上標籤,x 軸標題其實有點多餘。接下來你要在圖上加上國家標籤,這樣就能把所有座標軸都拿掉。
在這個練習中,你會遇到一個可能對你來說是新的概念:可以將新的資料集傳給單一幾何層(例如 geom_text()),讓該幾何層不使用初始 ggplot() 呼叫所提供的資料集。在這裡需要這麼做,是因為你只想在每支箭頭上加「一個」標籤。如果你使用原始資料集 ilo_data,每個國家會加上兩個標籤,因為資料集中每個國家有 2 筆觀測值,分別對應 1996 與 2006。
本練習屬於課程
在 Tidyverse 中以資料溝通
練習說明
- 已建立新的資料集
median_working_hours,因此每個國家只會有一個標籤。先用str()查看它的結構。 - 在新的
geom_text()呼叫中,將median_working_hours指定為data參數,以為每個國家加入標籤。- 正確指定
geom_text()所需的映射(aesthetics):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)
)