1.cowplotR包的安装,输入代码install.packages(“cowplot”),安装成功后,用library(“cowplot”)调用该R包。
2.以单个折线图为元素,做出折线图,原始数据如表1,代码如图1:
表1 原始数据
## | supp | does | len | SD | SE |
1 | OJ | 1 | 13.2 | 4.5 | 2.111871 |
2 | OJ | 2 | 22.7 | 3.9 | 1.977372 |
3 | OJ | 3 | 26.1 | 2.7 | 1.630951 |
4 | VC | 1 | 8 | 2.8 | 1.658312 |
5 | VC | 2 | 16.8 | 2.5 | 1.587451 |
6 | VC | 3 | 26.1 | 4.8 | 2.19089 |
library("ggplot2")
read.csv("C:\\Users\\26869\\Desktop\\折线图.csv")
df<-read.csv("C:\\Users\\26869\\Desktop\\折线图.csv")
df
ggplot(df,aes(x=does, y=len, colour=supp,shape=supp))+
geom_errorbar(aes(ymin=len-SE, ymax=len+SE),colour="black", width=.03,size=0.75)+
geom_line(size=0.75) +
geom_point(size=4,shape=21,fill="white")+
scale_colour_hue(name="Supplement type",
breaks=c("OJ", "VC"),
labels=c("Orange juice", "Ascorbic acid"),
l=40) +
expand_limits(y=0) +
scale_y_continuous(breaks=0:20*4) +
scale_x_continuous(breaks=0:10*0.5)+
theme_bw()+
theme(panel.grid.major=element_line(colour=NA),
panel.background = element_rect(fill = "transparent",colour = NA),
plot.background = element_rect(fill = "transparent",colour = NA),
panel.grid.minor = element_blank(),legend.justification=c(0.85,0.1),legend.position=c(0.85,0.1))
labs(x=NULL,y="长度",title=NULL)
图1 单个折线图代码
3.然后以相同的代码套用不同数据,得到若干个单个折线图(这里我们全部用一样的数据)
4.将上面单个折线图代码记为p1,然后调用cowplotR包,代码如图2(plot_grid()中的ncol和nrow可以调整为几行几列):
p1<-ggplot(df,aes(x=does, y=len, colour=supp,shape=supp))+
geom_errorbar(aes(ymin=len-SE, ymax=len+SE), colour="black",width=.03,size=0.75)+
geom_line(size=0.75) +
geom_point(size=4,shape=21,fill="white")+
scale_colour_hue(name="Supplement type",
breaks=c("OJ", "VC"),
labels=c("Orange juice", "Ascorbic acid"),
l=40) +
expand_limits(y=0) +
scale_y_continuous(breaks=0:20*4) +
scale_x_continuous(breaks=0:10*0.5)+
theme_bw()+
theme(panel.grid.major=element_line(colour=NA),
panel.background = element_rect(fill = "transparent",colour = NA),
plot.background = element_rect(fill = "transparent",colour = NA),
panel.grid.minor = element_blank())
labs(x=NULL,y="长度",title=NULL)
library(cowplot)
plot_grid(p1,p1,p1,p1,ncol=2,nrow=2)
图2 组合折线图代码
5.运行代码。结果如图3:
图3 结果图