我正在使用 ggplot 绘制一条曲线。我有计算平均值和 se 并存储在数据中的数据。然后我使用 ggplot 绘制曲线。到目前为止,一切看起来都很好。但是,我想将每个时间点的所有三个重复数据点分散到各自的平均误差条上。任何人都可以帮助我的查询。这是我的代码:
structure(list(values = c(5L, 3L, 2L, 6L, 4L, 1L, 5L, 3L, 1L,
25L, 15L, 10L, 30L, 17L, 9L, 27L, 14L, 8L, 75L, 45L, 20L, 80L,
50L, 25L, 90L, 50L, 30L, 150L, 100L, 50L, 160L, 110L, 60L, 170L,
120L, 70L), dose = structure(c(3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L,
1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L,
3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L), .Label = c("2.5",
"5", "10"), class = "factor"), time = c(0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 20L,
20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 30L, 30L, 30L, 30L, 30L,
30L, 30L, 30L, 30L)), row.names = c(NA, -36L), class = "data.frame")
my_data$dose <- as.factor(my_data$dose)
head(my_data)
library(dplyr)
data <- group_by(my_data, dose, time) %>%
summarise(
count = n(),
mean = mean(values, na.rm = TRUE),
sd = sd(values, na.rm = TRUE),
se = sd / sqrt(n())
)
data
p <- ggplot(data, aes(x=time, y=mean, group=dose)) +
geom_point(size = 1)+
geom_smooth(aes(linetype=dose), color = "black", se = F, size = 0.5)+
geom_errorbar(aes(ymin=mean - se, ymax=mean + se), width=1.8) +
labs(x ="sec", y = "Units") +
scale_x_continuous(breaks = seq(0, 35, 5), limits = c(-1, 35), expand = c(0, 0))+
scale_y_continuous(breaks = seq(0, 200, 20), limits = c(-10, 200), expand = c(0, 0))+
scale_linetype_manual(values=c( "dashed", "dotted", "solid"),
labels = c("2.5", "5", "10"))
p
最佳答案
要绘制的点存在于原始数据集 my_data
中,但不存在于聚合数据中。后者仅显示平均值。因此参数 data = my_data
必须传递给 geom_point
。
p <- ggplot(data, aes(x = time, y = mean, group = dose)) +
geom_point(data = my_data,
mapping = aes(x = time, y = values),
size = 1) +
geom_smooth(data = data,
mapping = aes(linetype = dose),
color = "black",
se = FALSE, size = 0.5)+
geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width=1.8) +
labs(x ="sec", y = "Units") +
scale_x_continuous(breaks = seq(0, 35, 5),
limits = c(-1, 35), expand = c(0, 0)) +
scale_y_continuous(breaks = seq(0, 200, 20),
limits = c(-10, 200), expand = c(0, 0)) +
scale_linetype_manual(values = c( "dashed", "dotted", "solid"),
labels = c("2.5", "5", "10"))
p
关于r - 如何在ggplot曲线中添加数据点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59710967/