Search code examples
rggplot2axis-labels

ggplot2 - how to add a specific axis tick?


Is there a way to add axis ticks discretely (i.e. just 1 at a time, not redefining the whole axis)? This would be very useful to dynamically show data without having to reconfigure the whole axis breaks every time.

I'm really hoping this can be done without grabbing the data from the grob! If not possible, I'd still appreciate a best practice on how to add specific ticks/numbers to an axis.


Solution

  • You can use the pretty function:

    library(ggplot2)
    
    extra_breaks <- c(6, 21)
    
    breaks <- sort(c(extra_breaks, with(mtcars, pretty(range(mpg)))))
    
    ggplot(mtcars, aes(x = cyl, y = mpg)) +
      geom_point() +
      scale_y_continuous(
        breaks = breaks,
        limits = range(breaks)
      )
    

    Created on 2020-05-10 by the reprex package (v0.3.0)