I would like to create a series of plots where the y-axis always runs between 0 and 10, but the plotted data may include values above 10. So for the series:
library(tibble)
df <- tibble(
y = c(0, 5, 10, 12, 5),
x = c(1, 2, 3, 4, 5)
)
library(ggplot2)
ggplot(df, aes(x = x, y = y)) +
geom_line() +
ylim(0, 10) # ylim is clearly not what I want
The line would have gone all the way up to 12, but this would extend above the highest value shown on the y-axis which is 10. I don't mean merely the highest break marked on the y-axis, but the actual y-axis itself only goes up to ten while the plotted data continues on to the highest value in df
.
Ideally, for each plot I make, the height of the y-axis would always remain the same, but the height of the plot would grow if there were values above ten.
A sort of example of what I am trying to achieve is shown in this question in the plot shown in the original question (that the user doesn't want). Except there the plotted values go below the minimum y-axis value, whereas I want the plotted values to go above the maximum plotted values.
BUT, FOR THE LOVE OF ALL THAT IS GOOD, WHY WOULD YOU WANT TO DO THAT?????
I intend to have 4 breaks marked on the y-axis which correspond to set guideline values. The data I am plotting is an index (lower is better than higher), and the values of the index don't have simple physical interpretations, except in relation to the guideline values. I don't want someone to read across to the y axis and say, well the value on plot A is 12 and the value on plot B is 13, so plot B is clearly worse than plot A.
Rather what I want is to give the impression, "Wow, these two values are literally off-the-scale", and so aren't really meaningful except in a general qualitative sense of "that's a little bit off the scale and that's a huge amount off the scale".
As I understand your question you want to "cap" the y axis at a value of 10. One option would be to set the limits conditionally based on the max value of the data (and fix the upper break at 10). And in case you are actually drawing an axis line the "new" cap=
argument of guide_axis
- introduced in ggplot2 3.5.0
- comes in handy which allows to cap the axis at the upper or lower break (or both):
df <- data.frame(
y = c(0, 5, 10, 12, 5),
x = c(1, 2, 3, 4, 5)
)
library(ggplot2)
ggplot(df, aes(x = x, y = y)) +
geom_line() +
scale_y_continuous(
breaks = seq(0, 10, 2),
guide = guide_axis(cap = "both"),
limits = \(x) {
if (max(x) < 10) c(0, 10) else c(0, max(x))
}
) +
theme(axis.line.y = element_line())