繪圖
當你把 Date 放在圖表的座標軸上時,會希望日期依照行事曆順序排列;使用 plot() 或 ggplot() 就會如此呈現。
在這個練習中,你會用 ggplot2 針對前面練習的 R 版本 releases 資料來畫圖。當座標軸上放的是 Date,有兩點很重要的差異:
如果要指定範圍(limits),它們必須是
Date物件。若要控制座標尺的行為,請使用
scale_x_date()函式。
試著做做看,並探索 R 發行版本的頻率。
本練習屬於課程
在 R 中處理日期與時間
練習說明
- 以
date欄作為aes()函式中x參數,繪製發行版本隨時間變化的圖。 - 透過指定範圍從
"2010-01-01"到"2014-01-01",放大檢視 2010 至 2014 年的期間。*注意:這些字串需要用as.Date()包起來,才能被解讀為Date物件。* - 透過指定
date_breaks為"10 years"與date_labels為"%Y",調整座標軸的標示方式。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
library(ggplot2)
# Set the x axis to the date column
ggplot(releases, aes(x = ___, y = type)) +
geom_line(aes(group = 1, color = factor(major)))
# Limit the axis to between 2010-01-01 and 2014-01-01
ggplot(releases, aes(x = date, y = type)) +
geom_line(aes(group = 1, color = factor(major))) +
xlim(as.Date(___), as.Date(___))
# Specify breaks every ten years and labels with "%Y"
ggplot(releases, aes(x = date, y = type)) +
geom_line(aes(group = 1, color = factor(major))) +
scale_x_date(date_breaks = ___, date_labels = ___)