0

In ggplot2, I want to add some axis preference to a theme, typically breaks and title, to have less repetitive code when I generate similar graphs. I have tried the following, but since scale_x_continuous does not return a theme object it does not work. Is there a way to make it work?

theme_set(theme_get() +
  scale_x_continuous('this is x',breaks=seq(0,10,by=2)))
ggplot(mpg,aes(x=displ,y=year))+geom_point()
Oneira
  • 1,365
  • 1
  • 14
  • 28
  • Could you provide some data and your complete code? You would get a better, adjusted, answer for your problem. – Paulo E. Cardoso Aug 12 '14 at 10:35
  • Why does the mpg embedded dataset does not fit as example? This is my complete code to try to set x axis title/breaks into the current theme – Oneira Aug 12 '14 at 10:44
  • try `set_default_scale` – baptiste Aug 12 '14 at 18:13
  • @baptiste does this function still exist in 0.9.3.1 ? I can only find doc for [0.8.9](http://www.inside-r.org/packages/cran/ggplot2/docs/set_default_scale) and got an error (`Error: could not find function`) when using it. – Oneira Aug 13 '14 at 02:00
  • @Lynda correct, sorry, I forgot. See [this discussion](http://stackoverflow.com/q/9944246/471093) for alternatives – baptiste Aug 13 '14 at 08:21

1 Answers1

1

You cannot do this with a theme. But you can save your axes preferences and then add them to your plots. Or define your favorite versions of ggplot in a function:

require(ggplot2)
# define my favorite axes
x.axis <- scale_x_continuous('this is x', breaks=seq(0,10,by=2))
y.axis <- scale_y_continuous('this is y', breaks=seq(1990,2010,by=3))
xy.ggplot <- function(...) ggplot(...) + x.axis + y.axis

# use axes in plots
ggplot(mpg,aes(x=displ,y=year)) + geom_point()
ggplot(mpg,aes(x=displ,y=year)) + geom_point() + x.axis
xy.ggplot(mpg,aes(x=displ,y=year)) + geom_point()

# you can also overwrite ggplot
ggplot <- function(...) ggplot2:::ggplot(...) + scale_x_continuous('this is x', breaks=seq(0,10,by=2))
# use your version
ggplot(mpg,aes(x=displ,y=year)) + geom_point()
# to get standard ggplot
ggplot2::ggplot(mpg,aes(x=displ,y=year)) + geom_point()
shadow
  • 21,823
  • 4
  • 63
  • 77