你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

R语言:ggplot2画带误差棒的组合折线图教程。

2021/12/21 13:41:13

1.cowplotR包的安装,输入代码install.packages(“cowplot”),安装成功后,用library(“cowplot”)调用该R包。

2.以单个折线图为元素,做出折线图,原始数据如表1,代码如图1:

表1 原始数据

##suppdoeslenSDSE
1OJ113.24.52.111871
2OJ222.73.91.977372
3OJ326.12.71.630951
4VC182.81.658312
5VC216.82.51.587451
6VC326.14.82.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 结果图