rggplot2

Adding numeric label to geom_hline in ggplot2


I have produced the graph pictured using the following code -

ggboxplot(xray50g, x = "SupplyingSite", y = "PercentPopAff", 
          fill = "SupplyingSite", legend = "none") +
  geom_point() +
  rotate_x_text(angle = 45) +
  # ADD HORIZONTAL LINE AT BASE MEAN
  geom_hline(yintercept = mean(xray50g$PercentPopAff), linetype = 2)

What I would like to do is label the horizontal geom_hline with it's numeric value so that it appears on the y axis.

I have provided an example of what I would like to achieve in the second image. Could somebody please help with the code to achieve this for my plot?

Thanks!


Solution

  • There's a really great answer that should help you out posted here. As long as you are okay with formatting the "extra tick" to match the existing axis, the easiest solution is to just create your axis breaks manually and specify within scale_y_continuous. See below where I use an example to label a vertical dotted line on the x-axis using this method.

    df <- data.frame(x=rnorm(1000, mean = 0.5))
    
    ggplot(df, aes(x)) +
        geom_histogram(binwidth = 0.1) +
        geom_vline(xintercept = 0.5, linetype=2) +
        scale_x_continuous(breaks=c(seq(from=-4,to=4,by=2), 0.5))
    

    enter image description here

    Again, for other methods, including those where you want the extra tick mark formatted differently than the rest of the axis, check the top answer here.