I have a function that returns a ggplot object that already has a line type scale. Now I want to change the scale. If I simply add a new scale, I get a message: "Scale for '...' is already present."
The question how to suppress that message has already been asked on stackoverflow (e.g. Supressing Warnings in scale_x_datetime). The only simple solution seems to be to suppress all messages - which I don't want, in order not to overlook something. So the natural alternative would be: Remove the present scale first, and then add another scale.
Can that be done easily?
Example (under the assumption that I'm not allowed to change the definition of f):
> f <- function() ggplot(mtcars, aes(x = mpg, y = hp)) + geom_point() + xlim(c(11, 34))
> g <- f()
> g + xlim(c(9, 36))
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
One possibility that seems to work with ggplot2-3.3.0:
> g <- ggplot(mtcars, aes(x = mpg, y = hp)) + geom_point() + xlim(c(11, 34))
> g$scales$scales <- list()
> g + xlim(c(9, 36))
I have the feeling that you are overlooking the most simple solution:
g.aux <- ggplot(mtcars, aes(x = mpg, y = hp)) + geom_point()
Then you could do either:
g1 <- g.aux + xlim(c(11, 34))
g2 <- g.aux + xlim(c(9, 36))
Or
g <- g.aux + xlim(c(11, 34))
#Do what you need with "g". Then redefine it as
g <- g.aux + xlim(c(9, 36))
##Do what you need with the new "g"
Hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With