Home > Mobile >  How to keep default axis labels but add an additional label in ggplot2
How to keep default axis labels but add an additional label in ggplot2

Time:04-10

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 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.

CodePudding user response:

By default ggplot2 will compute the default axis breaks in the following manner (Refer to enter image description here

  • Related