1

I would like to keep the default labels ggplot2 provides for Y-axis below, but always have a Y-axis tick and/or label at y = 100 to highlight the horizontal line intercept.

library(ggplot2)

maxValue <- 1000

df <- data.frame(
  var1 = seq(1, maxValue, by = 25),
  var2 = seq(1, maxValue, by = 50)
)

ggplot(df, aes(x = var1, y = var2)) +
  geom_point() +
  geom_hline(yintercept = 100, color = "red")

Created on 2022-04-09 by the reprex package (v2.0.1.9000)

Expected output:

enter image description here

Note that maxValue can be anything. So the solution to just increase in steps of 100 doesn't work. For example:

plot <- plot +
      scale_y_continuous(
        breaks = seq(0, max(df$y) + 100, 100),
        labels = as.character(seq(0, max(df$y) + 100, 100))
      )

This is because if the max value is 10000 or a similar big number like that, the number of labels will be overwhelming. This is why I would like to stay with the default Y-axis labels that ggplot2 provides and only add a single additional label at y = 100.

  • If it's OK to have the label on the opposite (= right) side of your y-axis, you can use `dup_axis` like so: `ggplot() + ... + scale_y_continuous(sec.axis = dup_axis(breaks = maxValue))` –  Apr 09 '22 at 18:46

1 Answers1

5

By default ggplot2 will compute the default axis breaks in the following manner (Refer to this answer for more details):

labeling::extended(min(df$var1), max(df$var1), m = 5))

We can just add your custom value 100 to this vector and pass it to scale_y_continous

def_breaks <- labeling::extended(min(df$var1), max(df$var1), m = 5)

ggplot(df, aes(x = var1, y = var2)) +
    geom_point() +
    geom_hline(yintercept = 100, color = "red") + 
    scale_y_continuous(breaks = c(100, def_breaks), 

                       # pass to minor breaks so that they are not messed up
                       minor_breaks = def_breaks)

enter image description here

AdroMine
  • 1,427
  • 5
  • 9
  • good answer. a possible improvement would be to add in logic to avoid overlapping custom and default values (e.g. the custom value must be at least 5% of the axis range different from each default value to display the custom value and all of the default values; otherwise don't display one of the 2 similar values). – filups21 Aug 11 '23 at 14:05