I want to set a ggplot's max y value while keeping the default min y but I need to use coord_cartesian
as I want to zoom in, not exclude any data from calculations.
I'm surprised that I couldn't find the answer to this. There are many questions answering how to expand limits to a certain value or set only one limit using scale_._..
but I can't find any using coord_cartesian
to set only one limit
For example; using the example plot from ?coord_cartesian
:
library(ggplot2)
p <- ggplot(mtcars, aes(disp, wt)) +
geom_point() +
geom_smooth()
I want the equivalent of
p + coord_cartesian(ylim = c(1.5, 4))
without having to set 1.5 as the min.
If I could use scale_y_continuous
I could use
p + scale_y_continuous(limits = c(NA, 4))
but this limits all data contributing to my smooth to values less than 4 which I don't want, and the equivalent p + coord_cartesian(ylim = c(NA, 4))
returns an error.
Is there an easy replacement?
I could also come up with a calculation based on the data of the min of the plot, but this could become complicated if I am faceting the plot or similar.
This issue was fixed in ggplot2 3.3.0 on 5-Mar-2020.
Now coord_cartesian(ylim = c(NA, 4))
runs without errors.
Example
library(ggplot2)
p <- ggplot(mtcars, aes(disp, wt)) +
geom_point() +
geom_smooth() +
coord_cartesian(ylim = c(NA, 4))
Below is the description of the feature in the NEWS file (bullet 2 under 'New features').
- All
coord_*()
functions withxlim
andylim
arguments now accept vectors withNA
as a placeholder for the minimum or maximum value (e.g.,ylim = c(0, NA)
would zoom the y-axis from 0 to the maximum value observed in the data). This mimics the behaviour of thelimits
argument in continuous scale functions (@paleolimbot, #2907).