tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.54k stars 2.03k forks source link

Set common scale parameters outside of the scale function #4269

Open clauswilke opened 4 years ago

clauswilke commented 4 years ago

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:

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:

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)

DanChaltiel commented 2 years ago

To add my two cents, the very message can be misleading as well as unnecessary:

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.

Even if it is not a warning, the message suggests that something has been replaced, thus overwritten. However, the two scales have only been merged since the name is intact.

A user could think that something is wrong although everything is fine.