重复测量图:叠加平均轨迹和误差线 (ggplot2)
Posted
技术标签:
【中文标题】重复测量图:叠加平均轨迹和误差线 (ggplot2)【英文标题】:Repeated measures plot: overlay mean trajectory and error bars (ggplot2) 【发布时间】:2021-11-10 13:42:27 【问题描述】:我制作了两张重复测量分数的图。第一个图是个人分数(即,绘制了每个参与者的分数)。第二个是平均分数和误差线图。我想组合这两个图,以便第二个图覆盖第一个图,或者将平均轨迹和误差条添加到第一个图。如何做到这一点?
示例数据和创建图的代码如下。
代码
# Renames variables for reshaping
names(data_wide) [names(data_wide) == "score.baseline"] <- "score.0"
names(data_wide) [names(data_wide) == "score.wave1"] <- "score.1"
names(data_wide) [names(data_wide) == "score.wave2"] <- "score.2"
names(data_wide) [names(data_wide) == "score.wave3"] <- "score.3"
#Convert wide-formatted data into long
data_long <- reshape(as.data.frame(data_wide),
idvar="ID",
varying=c("score.0", "score.1", "score.2", "score.3"),
direction="long")
# Prepare means data
data_long.group <- data_long %>%
group_by(time) %>%
summarise(
score_mean = (mean(score, na.rm=TRUE)),
score_sd = (sd(score, na.rm=TRUE))
)
# Plot individual scores
ggplot(data_long, aes(x = factor(time), y = score, color = as.factor(ID), group = ID)) +
geom_line(size=0.2) +
theme_classic(base_size = 18) +
theme(legend.position = "none") +
labs(title = "Trajectories", y = "data score", x = "Wave")
# Plot group-level means and SDs
ggplot(data_long.group, aes(x = time, y = score_mean)) +
geom_line(size=0.2) +
theme_classic(base_size = 18) +
theme(legend.position = "none") +
labs(title = "Trajectories", y = "data score", x = "Wave") +
geom_errorbar(aes(ymin=score_mean-score_sd, ymax=score_mean+score_sd), width=.2,
position=position_dodge(0.05))
示例数据
data_wide <- structure(
list(ID = c(1, 2, 3, 4, 5, 6),
score.baseline = c(4, 4, 5, 4, 6, 4),
score.wave1 = c(3.5, 5.67, 5.33, 4, 6.67, 4.5),
score.wave2 = c(4, 5, NA, 4, 6.67, 4),
score.wave3 = c(6, 6, 4.67, 4.33, 6.67, 3)),
row.names = c(1L, 2L, 3L, 4L, 5L, 6L),
class = c("data.frame"))
【问题讨论】:
【参考方案1】:您只需组合代码即可。但是,由于美学是在单个 ggplot 调用中继承的,因此您必须 NULL
ify 那些在相应层中不需要的部分
ggplot(data_long, aes(x = factor(time),
y = score,
color = as.factor(ID),
group = ID)) +
geom_line(size = 0.2) +
theme_classic(base_size = 18) +
theme(legend.position = "none") +
labs(title = "Trajectories", y = "data score", x = "Wave") +
geom_line(data = data_long.group,
mapping = aes(x = time,
y = score_mean,
group = NULL,
color = NULL),
size = 0.2) +
theme_classic(base_size = 18) +
theme(legend.position = "none") +
labs(title = "Trajectories", y = "data score", x = "Wave") +
geom_errorbar(data = data_long.group,
mapping = aes(ymin = score_mean - score_sd,
ymax = score_mean + score_sd,
y = NULL,
group = NULL,
color = NULL),
width = .2,
position = position_dodge(0.05))
【讨论】:
以上是关于重复测量图:叠加平均轨迹和误差线 (ggplot2)的主要内容,如果未能解决你的问题,请参考以下文章
画图笔记:ggplot2优化柱形图(添加误差线、差异比较分析)