Description
A problem that pops up repeatedly in different contexts is that we may want to adjust certain scale parameters without explicitly calling a scale function. We already have some support for this, e.g. with xlim()
to set limits on the x position scale or xlab()
to set its title, but there are numerous other scenarios where the same problem arises. Here are some examples:
- We may want to set scale expansions: Shortcut for
scale_y_continuous(expand = expansion(c(0, 0.05))
#3962 - We may want to set breaks or limits, including for non-position scale functions: WIP: Register default scales via themes #3973 (comment)
- We may want to specify
drop = FALSE
on discrete scales: Inconsistent colours in filled contour plot #4268 (comment)
It would be good if we could come up with a generic approach to these issues. I note that xlim()
and xlab()
use entirely different implementation approaches currently, so that's not promising:
-
xlim()
andylim()
use theggplot2:::limits()
function to automatically generate a scale function and give it the appropriate parameter settings:
Lines 112 to 160 in 3be0acc
-
xlab()
andylab()
ultimately feed their info to theupdate_labels()
function, which writes to a specialplot$labels
field that the layout reads from:
Lines 13 to 17 in 3aa2937
Line 170 in 660aad2
Lines 107 to 113 in b76fa96
Neither approach generalizes directly to the other use cases. I also have concerns about the way xlim()
and ylim()
are implemented, because the fact that they add explicit scales functions is not obvious and can lead to strange behavior. See e.g. the following reprex, where in the first plot the call to scale_x_continuous()
overwrites the xlim()
call but in the second plot the xlab()
call is not overwritten:
library(ggplot2)
ggplot(mtcars, aes(disp, mpg)) +
geom_point() +
xlim(100, 300) +
scale_x_continuous(name = "Displacement")
#> Scale for 'x' is already present. Adding another scale for 'x', which will
#> replace the existing scale.
ggplot(mtcars, aes(disp, mpg)) +
geom_point() +
xlab("Displacement") +
scale_x_continuous(limits = c(100, 300))
#> Warning: Removed 16 rows containing missing values (geom_point).
Created on 2020-11-17 by the reprex package (v0.3.0)