利用ggplot2绘制折线图(均值+误差棒)

由于实验需要,帮师姐画了一张折线图。
特此感谢师姐提供数据给我锻炼的机会!

成品图如下

image.png

直接上代码

1. 读入数据

library(ggplot2)
library(Rmisc)
library(cowplot)

# 读入数据
W1 <- read.csv("W1.txt", sep = "\t", header = T)
W2 <- read.csv("W2.txt", sep = "\t", header = T)
W3 <- read.csv("W3.txt", sep = "\t", header = T)

> head(W1)
#   Subject     Value Time
# 1       A   0.00000    1
# 2       A   0.00000    1
# 3       A   0.00000    1
# 4       A   0.00000    1
# 5       B 236.82228    1
# 6       B  97.07076    1

2. 计算标准差

# summarySE 计算标准差和标准误差以及95%的置信区间.
tgc1 <- summarySE(W1, measurevar="Value", groupvars=c("Subject","Time"))
tgc2 <- summarySE(W2, measurevar="Value", groupvars=c("Subject","Time"))
tgc3 <- summarySE(W3, measurevar="Value", groupvars=c("Subject","Time"))

> head(tgc1)
  Subject Time N     Value        sd       se       ci
1       A    1 4   0.00000   0.00000  0.00000   0.0000
2       A    2 4   0.00000   0.00000  0.00000   0.0000
3       A    3 4  69.62475  63.42117 31.71059 100.9172
4       A    4 4   0.00000   0.00000  0.00000   0.0000
5       A    5 4   0.00000   0.00000  0.00000   0.0000
6       B    1 4 252.48276 123.24463 61.62232 196.1097

3. 绘制折线图

P1 <- ggplot(tgc1, aes(x=Time, y=Value, colour=Subject)) +   
  geom_errorbar(aes(ymin=Value-se, ymax=Value+se), width=.1) +
  geom_line() +
  geom_point()+
  theme_bw()

P2 <- ggplot(tgc2, aes(x=Time, y=Value, colour=Subject)) +   
  geom_errorbar(aes(ymin=Value-se, ymax=Value+se), width=.1) +
  geom_line() +
  geom_point()+
  theme_bw()

P3 <- ggplot(tgc3, aes(x=Time, y=Value, colour=Subject)) +   
  geom_errorbar(aes(ymin=Value-se, ymax=Value+se), width=.1) +
  geom_line() +
  geom_point()+
  theme_bw()

plot_grid(P1,P2,P3, nrow = 1, labels = LETTERS[1:3], align = c("v", "h"))

结果如图所示,从图中可以看出,不能太方便得进行横向和纵向比较。

image.png

所以计划采用分面绘图facet_grid()

4. 分面

横纵向比较时统一了Y轴范围(0~1100)。

P4 <- P1+
  coord_cartesian(ylim = c(0, 1100))+
  labs(x= 'Time (d)', y = 'OD')+
  facet_grid(.~Subject)+
  theme_bw()

P5 <- P2+
  coord_cartesian(ylim = c(0, 1100))+
  labs(x= 'Time (d)', y = 'OD')+
  facet_grid(.~Subject)+
  theme_bw()

P6 <- P3+
  coord_cartesian(ylim = c(0, 1100))+
  labs(x= 'Time (d)', y = 'OD')+
  facet_grid(.~Subject)+
  theme_bw()
  
plot_grid(P4,P5,P6, ncol = 1, labels = LETTERS[1:3], align = c("v", "h"))
image.png

你可能感兴趣的:(利用ggplot2绘制折线图(均值+误差棒))