R语言 在ggplot中格式化箱形图中的水平线的问题

k7fdbhmy  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(216)

我不知道为什么,但是我没有在箱线图上添加一条红色虚线来表示y值的平均值:

df %>% 

  ggplot(aes(x = month, y= dep_delay)) +
  theme(panel.grid.major.y = element_line(color = "darkgrey",
                                          size = 0.5,
                                          linetype = 2)) +
  geom_boxplot(colour = '#003399', varwidth=T, fill="lightblue")+
  geom_hline(aes(yintercept=mean(dep_delay), linetype = "dashed", color = "red")) +
  labs(title="Departure delays in Newark airport per month", 
       x="", y = "duration of delays")

参数linetype和color在右边显示为图例,不会影响我的线。我还尝试了'geom_hline(yintercept=mean(dep_delay,linetype =“dashed”,color =“red”))'.

有人知道我哪里做错了吗

bwleehnv

bwleehnv1#

括号与geom_hline错位; colorlinetype不应包含在aes()中。aes()应用于引用变量(例如Wind)。将“red”包含在aes()中会使ggplot认为“red”是变量。
还要注意的是,element_line(size())从ggplot 2 3.4.0开始已经被弃用。--请改用linewidth

library(tidyverse)
data(airquality)
df <- airquality %>%
  mutate(Month = factor(Month))

mean(df$Wind)
#> [1] 9.957516

df %>% 
  ggplot(aes(x = Month, y = Wind)) +
  theme(panel.grid.major.y = element_line(color = "darkgrey",
                                          linewidth = 0.5, # don't use size
                                          linetype = 2)) +
  geom_boxplot(colour = '#003399', varwidth=T, fill="lightblue")+
  geom_hline(aes(yintercept=mean(Wind)), linetype = "dashed", color = "red") + # good
  #geom_hline(aes(yintercept=mean(Wind), linetype = "dashed", color = "red")) + # bad
  labs(title="Departure delays in Newark airport per month", 
       x="", y = "duration of delays")

相关问题