在 R 中的折线图中添加误差线(ggplot)
Posted
技术标签:
【中文标题】在 R 中的折线图中添加误差线(ggplot)【英文标题】:Addition of errorbars in line graph in R (ggplot) 【发布时间】:2021-10-07 12:04:32 【问题描述】:我一直在尝试创建一个图表,其中包含一些测量值的重复(用点显示)、平均值以及它们如何随时间变化(用线显示),然后我想在图中添加误差线。 这就是我所拥有的:
名为 brixtwenty 的 tibble 包含所有复制的所有数据。这些是列的名称: 治疗天数cc
This one is the data
dput(brixtwenty)
structure(list(Treatment = c("control", "control", "control",
"control", "control", "control", "control", "control", "control",
"control", "control", "control", "control", "control", "control",
"EM", "EM", "EM", "EM", "EM", "EM", "EM", "EM", "EM", "EM", "EM",
"EM", "EM", "EM", "EM"), Brix = c("20", "20", "20", "20", "20",
"20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20",
"20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20",
"20", "20", "20"), Days = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4,
4, 5, 5, 5, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5), cc = c(285.091399590441,
258.04137922621, 158.919577827924, 666.610152272179, 592.054531152063,
395.766563783474, 726.762264553872, 731.837900223478, 470.645533209648,
606.49690396958, 740.720133098691, 464.116384721947, 406.655732539073,
342.175727545533, 167.083656188129, 703.846110644974, 523.016679600599,
535.618627097046, 461.764854893598, 500.47182351152, 465.279713162811,
441.200628089279, 921.867730585244, 871.728015690802, 468.771771230955,
851.874066968395, 982.927187232172, 1030.31118691569, 1144.31011951096,
1159.25979680224)), row.names = c(NA, -30L), class = c("tbl_df",
"tbl", "data.frame"))
btwsummary <- brixtwenty %>%
group_by(Days, Treatment) %>%
summarise(mean=mean(cc), sd=sd(cc))
graph <- ggplot(brixtwenty, aes(x=Days, y=cc, color=Treatment)) +
geom_point() +
geom_line(data = btwsummary, aes(x=Days, y=mean, color=Treatment))+
geom_errorbar(data=btwsummary, aes(ymin=mean-sd, ymax=mean+sd, color=Treatment))
错误:美学长度必须为 1 或与数据 (10) 相同:y
如果没有误差条的部分,我会得到带有点和线的图表,用于两种处理。
有人可以帮我解决这个问题吗?
谢谢!
【问题讨论】:
请以dput()
格式提供您的数据。访问How to make a great R reproducible example。
感谢您的建议。我现在已经添加了数据。让我知道是否还有其他事情可以让我的帖子更清晰!
【参考方案1】:
为了让您入门,请阅读 ggplot 的层继承。在许多情况下,下层可能与上层冲突,尤其是上层美学定义。您始终可以做的是在每一层中明确指定您正在使用的数据和美学。 (我知道很多人会告诉你这不是这样做的方法,但它可以确保你从可行的东西开始,然后再让它变得更优雅)。
在你的情况下:
library(ggplot2)
ggplot() + # the basic ggplot canvas
geom_point(data = brixtwenty, aes(x=Days, y=cc, color=Treatment)) + # your points
geom_line(data = btwsummary, aes(x=Days, y=mean, color=Treatment)) + # your summary mid(mean)point line
geom_errorbar(data = btwsummary, aes(x = Days, ymin = mean-sd, ymax=mean+sd, color = Treatment)) # the errorbars you want to show based on your btwsummary
这给了你:
【讨论】:
以上是关于在 R 中的折线图中添加误差线(ggplot)的主要内容,如果未能解决你的问题,请参考以下文章