折线图一般用于描述一维变量随着某一连续变量(通常为时间)变化的情况。即折线图最适合描述时间序列数据的变化情况。也可随着有序离散变量变化。本文介绍ggplot2包的geom_line()函数绘制折线图。绘制方法是首先调用ggplot()函数选定数据集,并在aes参数中指明横轴纵轴。然后调用条形图函数geom_line()函数绘制出基本折线图。
示例案例
#利用ggplot2包自带的数据BOD绘制折线图
#加载ggplot2包
library(ggplot2)
#如未安装,则用install.packages("ggplot2")安装
单条折线图
#基本绘图
#连续变量
ggplot(BOD, aes(x=Time, y=demand)) +
geom_line()
#离散变量的情况
BOD1 <- BOD # 赋值数据
BOD1$Time <- factor(BOD1$Time)#变量因子化
#给折线图加上方框/点
ggplot(BOD, aes(x=Time, y=demand)) +
geom_line() +
geom_point(size=4, shape=15)
多条折线图
#创建数据集
supp1=c("OJ","OJ","OJ","VC","VC","VC")
dose1=c(0.5,1.0,2.0,0.5,1.0,2.0)
length1=c(13.23,22.70,26.06,7.98,16.77,26.14)
tgg<-data.frame(supp1,dose1,length1)
#查看数据集tgg
head(tgg)
#绘图
ggplot(tgg, aes(x=factor(dose1), y=length1, colour=supp1,group=supp1)) +
geom_line(size=2) #x为药剂剂量,并非连续型变量
#设置shape参数
ggplot(tgg, aes(x=dose1, y=length1, color=supp1,shape=supp1)) +
geom_line() +
geom_point(size=4)
#设置fill参数
ggplot(tgg, aes(x=dose1, y=length1, color=supp1,fill=supp1)) +
geom_line() +
geom_point(size=4)
#美化图
ggplot(tgg, aes(x=dose1, y=length1, shape=supp1)) +
geom_line(position=position_dodge(0.2)) + #减淡线增加0.2
geom_point(position=position_dodge(0.2), size=4)+ #控制两线各向左向右移0.2的距离(保证不会点重叠)
theme_bw()
参考文献
[1] https://blog.csdn.net/zx403413599/article/details/46854275?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.base&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.base
[2] Robert I. Kabacoff (著). R语言实战(高涛/肖楠/陈钢 译). 北京: 人民邮电出版社.