Reputation: 65
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:
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
.
Upvotes: 3
Views: 798
Reputation: 1527
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)
Upvotes: 6