如何在1个图中绘制带有CI的2个平均线图

问题描述 投票:0回答:1

我试图在一个情节中用CI绘制2行方法。我使用gplots有功能plotmeans绘制一条线,但我只能在一个绘图中绘制一条线。有人可以帮忙吗?非常感谢

这是我的数据的一个例子

Group  MC  MB
G1     5    10
G2     8    8
G3     14   7  
G4     20   6
G1     10   15
G2     16   13   
G3     30   9
G4     25   7
G1     15   29
G2     20   22
G3     25   20
G4     35   15 

我想将MC和MB绘制为一条线,其值是每组的平均值和CI。 xlab将是groupylabMCMB的价值。

我希望像这样的enter image description here

非常感谢。

r plot mean confidence-interval
1个回答
0
投票

这可以通过tidyr,dplyr和ggplot2的组合来完成。

# Your data
group <- c("G1", "G2", "G3", "G4", "G1", "G2", "G3", "G4", "G1", "G2", "G3", "G4")
mc <- c(5, 8, 14, 20, 10, 16, 30, 25, 15, 20, 25, 35)
mb <- c(10, 8, 7, 6, 15, 13, 9, 7, 29, 22, 20, 15)
df <- data.frame(group, mc, mb)

首先,我们使用列类别(cat)和值将数据收集到长格式。

# Requires library "tidyr"
library(tidyr)

# Gathering data
df_gathered <- gather(df, cat, value, 2:3)

接下来,您计算每个组和类别组合的平均值和误差:

# Requires the library "dplyr"
library(dplyr)

# Calculating mean and error by group
df_mean_by_group <- df_gathered %>% 
  group_by(group, cat) %>%
  summarise(mean = mean(value), error = qnorm(0.975)*sd(value)/length(value))

最后,我们绘制按类别对行进行分组(连接它们),并按类别对它们进行着色:

# Requires "ggplot2"
library(ggplot2)

# Plotting it all
ggplot(df_mean_by_group, aes(x=group, y=mean, colour=cat, group=cat)) + 
  geom_errorbar(aes(ymin=mean-error, ymax=mean+error), colour="black", width=.1) +
  geom_line() +
  geom_point(size=3)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.