r - 如何在ggplot曲线中添加数据点?

标签 r ggplot2

我正在使用 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

enter image description here

最佳答案

要绘制的点存在于原始数据集 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

enter image description here

关于r - 如何在ggplot曲线中添加数据点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59710967/

相关文章:

r - 在绘图区域外添加文本

r - 在barplot ggplot中手动设置每组颜色

r - ggplot2:如何在回归线上弯曲小高斯密度?

c++ - R CMD SHLIB 'undefined reference' 并且不为 SWIG 生成的 R 包装器生成 .so/.dll

r - 查看每个 id 是否有任何非 NA 值

r - 在 R 中使用字符和列总和约束的 lpSolve

r - 如何将 data.table 的每一行与向量相乘

r - 条形图中条形之间的特定空间 - ggplot2 - R

r - 如何在 R 中创建时间序列?

r - 如何使用 prop.table() 输出来计算期望值