r - 使用“聚合”功能绘制线图
问题描述
我正在尝试为两组数据(治疗与控制)绘制带有误差线的线图。总共有 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()
到您的工作目录。
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()
屈服
推荐阅读
- java - 我的 java 代码在线程“main”java.lang.ArrayIndexOutOfBoundsException 中抛出异常?
- php - Prestashop 错误:升级到 1.7.6.4 后无法编辑或创建新产品
- php - 我调用了数据并尝试使用 fetch_assoc 但没有出现
- python-3.x - 是什么原因导致损失函数和度量在训练过程中都使用了相同的函数,但结果却不同?
- ruby-on-rails - 从 rails RJS 访问 Stimulus JS
- javascript - 可选的捕获组直到行尾
- python-3.x - 当我只想更新一个时,不需要同时更新列表的所有元素
- javascript - bootstrap 可以用 Angular js 折叠
- javascript - 错误:Auth0 create-react-app 中的“需要域选项”
- c++ - c ++如何在运行时链接函数声明?