使用 "aggregate" 函数绘制线图

Using the "aggregate" function for drawing line plots

我正在尝试为两组数据(治疗与对照)绘制带有误差线的线图。总共有 20 个周期,10 个试用周期 (TP) 和 10 个正式周期 (P),我想展示组意味着如何随时间变化。为简单起见,以下数据框包括 3 个试用期(TP1、TP5、TP10)和 3 个正式期(P1、P5、P10)。

下面是我的代码。我的问题是“聚合”函数通过将周期作为字符串重新排序来改变周期的顺序,这打乱了时间趋势——我希望它们按 TP1->TP5->TP10->P1->P5-> 排序P10

我想这并不太棘手,但我只是被卡住了。如果有人能告诉我如何解决这个问题,我将不胜感激。

此外:由于总共有 20 个周期,绘制误差带(或 CI 带)而不是许多误差线可能看起来更好。有办法吗?

df <- data.frame(Condition=c(rep("Treatment", 10), rep("Control", 10)), 
               TP1=rnorm(20, 1, 1), TP5=rnorm(20, 5, 1), TP10=rnorm(20, 10, 1), 
               P1=rnorm(20, 1, 1), P5=rnorm(20, 5, 1), P10=rnorm(20, 10, 1))

temp <- tidyr::gather(df, Period, x, -Condition)

m <- aggregate(x~Period + Condition, temp, mean)

st.err <- function(x) sqrt(var(x)/length(x))

se <- aggregate(x~Period + Condition, temp, st.err)

ci.data <- cbind(m, se[, 3])

colnames(ci.data) <-  c("Period", "Condition", "Mean", "SE")

library(ggplot2)
ggplot(data=ci.data, aes(x=Period, y=Mean, group=Condition, color=Condition)) + 
  geom_line() + 
  geom_point() +  
  geom_errorbar(aes(ymin=Mean-SE, ymax=Mean + SE), 
                width=.1, position=position_dodge(0.05)) 

使用reshape2::melt()将句点转换为更好排序的因子。这里不需要更多聚合,因为 geom_smooth() 正在做你想做的事。

df.long <- reshape2::melt(df, "Condition", variable.name="Period", value.name = "x")

library(ggplot2)
ggplot(df.long, aes(x=Period, y=x, group=Condition, color=Condition, fill=Condition)) + 
  geom_smooth(method="loess", level=0.95, alpha=.2) 

屈服

数据

set.seed(42)  # for sake of reproducibility
df <- data.frame(Condition=c(rep("Treatment", 10), rep("Control", 10)), 
               TP1=rnorm(20, 1, 1), TP5=rnorm(20, 5, 1), TP10=rnorm(20, 10, 1), 
               P1=rnorm(20, 1, 1), P5=rnorm(20, 5, 1), P10=rnorm(20, 10, 1))

编辑

对于较大的数据集,您可以使用 span 调整平滑度。导出情节,例如用 png() 到你的 working directory.

png("test.png", width=1080, height=720, res=100)
ggplot(df.long, aes(x=Period, y=x, group=Condition, color=Condition, fill=Condition)) + 
  geom_smooth(method="loess", level=0.95, alpha=.2, span=.2) +
  labs(title="My Plot")
dev.off()

屈服