Bluetail
Bluetail

Reputation: 1291

problem with formatting the horizontal line in boxplot in ggplot

I dont know why but I'm failing to add a dashed red line representing the mean of the y-values to my boxplot:

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")

the parameters linetype and color show up as a legend on the right without affecting my line. I have also tried 'geom_hline(yintercept=mean(dep_delay,linetype = "dashed", color = "red"))'. enter image description here

does anyone know what I'm doing wrong?

Upvotes: 0

Views: 167

Answers (1)

jrcalabrese
jrcalabrese

Reputation: 2321

A misplaced parenthesis with geom_hline; color and linetype should not be included within aes(). aes() should be used to reference variables (e.g. Wind). Including "red" within aes() makes ggplot think that "red" is a variable.

Also be aware that element_line(size()) has been deprecated as of ggplot2 3.4.0. -- use linewidth instead.

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")

enter image description here

Upvotes: 2

Related Questions