Search code examples
rggplot2histogram

Ggplot mangles histogram when geom_vline is added


I need to produce a set of histograms where there is a vertical line, in some cases far away from the values of the histogram, sort of like this:

hist(mtcars$mpg, breaks = 15, xlim=c(0,160))
abline(v=150, lwd=2, lty=2, col="blue")

In base R if I extend the x axis and add the vertical line, the histogram itself does not change.

Ideally I would do the plots with ggplot instead of base R, but if I do this, on adding the vertical line the histogram itself changes:

ggplot(data = mtcars, aes(x=mpg))+
  geom_vline(xintercept = 150, color= "blue", linetype="dashed")+
  scale_x_continuous(c(0,160))+
  geom_histogram(binwidth = 15, color="black", fill="white")

(First histogram is in base R, second with ggplot)

enter image description here

How can I produce the same histogram as in base R, with the vertical line, in ggplot?


Solution

  • Here is the exact same plot with ggplot2. The main task was to set the correct binwidth and breaks:

    library(ggplot2)
    
    ggplot(mtcars, aes(x = mpg)) +
      geom_histogram(binwidth = 2, color = "black", fill = "grey80", breaks = seq(0, 160, by = 2)) +
      geom_vline(xintercept = 150, linetype = "dashed", color = "blue", size = 1) +
      scale_x_continuous(limits = c(-10, 160), expand = c(0, 0)) +
      scale_y_continuous(limits = c(0, 7.5), expand = c(0, 0)) +
      theme_classic()
    

    enter image description here