Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a scale from a ggplot object?

Tags:

r

ggplot2

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.
like image 321
jarauh Avatar asked Oct 23 '25 16:10

jarauh


2 Answers

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))
like image 143
jarauh Avatar answered Oct 25 '25 05:10

jarauh


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

like image 29
davidnortes Avatar answered Oct 25 '25 04:10

davidnortes