《R数据可视化手册》学习笔记4---折线图(2)

写在前面。

折线图通常用来反映两个连续型变量的依存关系。其中,x轴对应自变量y轴对应因变量


折线图

折线图的x轴一般是连续型变量,如时间变量药剂量等,当然也可以是有序离散型变量


多重折线图

绘制多重折线图,就是在简单折线图的基础上,将另外一个离散型分组变量分配给线条颜色colour或者线型linetype

示例数据是ToothGrowth数据集,

head(ToothGrowth)
   len supp dose
1  4.2   VC  0.5
2 11.5   VC  0.5
3  7.3   VC  0.5
4  5.8   VC  0.5
5  6.4   VC  0.5
6 10.0   VC  0.5

先使用plyr包的ddply函数进行了数据汇总:

library(plyr)
tg <- ddply(ToothGrowth, c("supp", "dose"), summarise,  length= mean(len) )
> head(tg)
  supp dose length
1   OJ  0.5  13.23
2   OJ  1.0  22.70
3   OJ  2.0  26.06
4   VC  0.5   7.98
5   VC  1.0  16.77
6   VC  2.0  26.14
  • supp映射给颜色
ggplot(data=tg , aes(x = dose , y = length,  colour= supp)) + geom_line()

[图片上传失败...(image-d4cca0-1695170397514)]

  • supp映射给线型
ggplot(data=tg , aes(x = dose , y = length,  linetype= supp)) + geom_line()

[图片上传失败...(image-ea6e24-1695170397514)]

  • 再提一嘴,如果x变量是因子型,需要给group指定分组变量
> ggplot(data=tg , aes(x = factor(dose) , y = length,  linetype= supp)) + geom_line()
`geom_line()`: Each group consists of only one observation.
ℹ Do you need to adjust the group aesthetic?
ggplot(data=tg , aes(x = factor(dose) , y = length,  linetype= supp, group = supp)) + geom_line()

[图片上传失败...(image-6a4360-1695170397514)]

  • 当指定了错误分组变量或者未指定分组变量,会出现锯齿形线型,这是一个x值对应了多个y值。
ggplot(data=tg , aes(x = dose , y = length)) + geom_line()

[图片上传失败...(image-a127f8-1695170397514)]


以上。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容