绘图
如果在图形坐标轴上绘制 Date,您会期望日期按日历顺序排列,使用 plot() 或 ggplot() 正是如此。
本练习中,您将用 ggplot2 基于前面练习的 R 版本 releases 数据绘制一些图。 当坐标轴上是 Date 时有两点重要区别:
如果要指定取值范围,必须使用
Date对象。若要控制刻度的行为,请使用
scale_x_date()函数。
请在本练习中动手探索 R 版本发布的频率。
本练习是课程的一部分
在 R 中处理日期和时间
练习说明
- 通过将
aes()函数的x参数设置为date列,绘制发布时间随时间变化的图。 - 通过将范围限制设为从
"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 = ___)