[英]How to draw a 2 mean line plots with CI in 1 plot
这可以通过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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.