0

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?

1
  • I think it should be aes(yintercept = mean(dep_delay)), linetype = "dashed", colour = "red" to get it right, i.e. move the parenthesis. You're now mapping them to scales instead of using them as 'plain' parameters. Commented Dec 11, 2022 at 15:26

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.