3

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.
jarauh
  • 1,836
  • 22
  • 30

2 Answers2

4

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))
jarauh
  • 1,836
  • 22
  • 30
0

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

davidnortes
  • 872
  • 6
  • 14
  • The problem is that in my setting I don't have direct access to `g.aux`. Instead, I only have a function that gives `g1` to me. Sorry for not making that clear enough in the question. – jarauh Apr 09 '20 at 10:46
  • I see... Have you seen this answer? https://stackoverflow.com/questions/41940000/modifying-ggplot-objects-after-creation – davidnortes Apr 09 '20 at 11:04
  • Thanks for the link. So the question is: If I "build" the plot, is it easier to manipulate afterwards? I will look into that. – jarauh Apr 10 '20 at 13:03