在ggplot的箱线图中添加平均值

时间:2019-02-24 16:09:13

标签: r ggplot2

我试图将均值添加到ggplot中的箱线图中,但均值添加到箱线图旁边而不是框内。不幸的是,我在互联网上找不到任何解决方案。有人能帮我吗? 我的数据如下:

dput(test2)
structure(list(station = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), 
    date = c("01.01.2018", "02.01.2018", "03.01.2018", "04.01.2018", 
    "05.01.2018", "01.01.2018", "02.01.2018", "03.01.2018", "04.01.2018", 
    "05.01.2018", "01.01.2018", "02.01.2018", "03.01.2018", "04.01.2018", 
    "05.01.2018", "01.01.2018", "02.01.2018", "03.01.2018", "04.01.2018", 
    "05.01.2018", "01.01.2018", "02.01.2018", "03.01.2018", "04.01.2018", 
    "05.01.2018", "01.01.2018", "02.01.2018", "03.01.2018", "04.01.2018", 
    "05.01.2018", "01.01.2018", "02.01.2018", "03.01.2018", "04.01.2018", 
    "05.01.2018", "01.01.2018", "02.01.2018", "03.01.2018", "04.01.2018", 
    "05.01.2018"), number = c(0, 0, 1.25, 0, 0, 0.761636107, 
    0.917030568, 0.526315789, 0.462555066, 0.728476821, 0.625, 
    3.75, 1.276595745, 0, 0, 1.636363636, 1.25748503, 0.176470588, 
    1.220930233, 1.031518625, 1, 0, 4, 1, 0, 0.174978128, 0.131004367, 
    0.197368421, 0.396475771, 0.198675497, 1.25, 1.25, 0, 0, 
    0, 0, 0.718562874, 0, 0.523255814, 0), time = c(1L, 1L, 1L, 
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 
    4L, 4L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 
    3L, 3L, 4L, 4L, 4L, 4L, 4L)), class = "data.frame", row.names = c(NA, 
-40L))

这是我的代码:

options(stringsAsFactors = FALSE) 
input5 <- "C:\\Users\\test2.csv" 

test2<- read.csv(input5, sep=";") 

library(lubridate) 
library(dplyr) 
library(ggplot2) 

means <- aggregate(number ~ station, test2, mean) 
p2 <- test2 %>% 
  mutate(
    date = dmy(date),
    station = as.factor(station), 
    time = as.factor(time)
  ) %>% 
  group_by(time) %>% 
  ggplot(aes(x = station, y = number, fill = time)) + 
  geom_boxplot() + 
  theme_bw() + 
  stat_summary(fun.y = mean, colour = "red", geom = "point", shape = 16, size = 1, show_guide = FALSE) + 
  theme(legend.position = "none") 
p2

0 个答案:

没有答案