[英]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.