25

Theming for ggplot2 makes it quite easy to relegate the need for multiple or repetitive + opt()... lines. However, I would like to know if there is a way to define defaults for geoms and scale colors. Instead of having to write ...+ scale_fill_manual() for each plot, I'd like to be able to set it and forget it. Similarly, I'd like to be able to set geom options so I don't have to retype (or forget to retype) things like geom_text(...,size=3,color="white")

Update:

For scales, it seems at some point that there was a method:

set_default_scale("colour", "discrete", "grey")

But this function doesn't seem to exist in the most recent version of ggplot2.

Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255

3 Answers3

24

There is another method for this now. You can essentially overwrite any aesthetics scale, for example:

scale_colour_discrete <- function(...) scale_colour_brewer(..., palette="Set2")
scale_fill_discrete <- function(...) scale_fill_brewer(... , palette="Set2")

Now, your aesthetics will be coloured or filled following that behaviour.'

As per: https://groups.google.com/forum/?fromgroups=#!topic/ggplot2/w0Tl0T_U9dI

With respect to defaults to geoms, you can use update_geom_defaults, for example:

update_geom_defaults("line",   list(size = 2))
Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
4

I can't think of anything useful for the geoms, but for the scales, one option would be to use the fact that components of ggplots are all simply R objects that can be saved, stored and reassigned like any other.

So you could perhaps create your own collection of "default" versions of many scales, like:

sfmDefault <- scale_fill_manual(...)
scmDefault <- scale_colour_manual(...)

etc. with your desired default values. Put them in your .RProfile or wherever and use them as needed.

joran
  • 169,992
  • 32
  • 429
  • 468
  • This is the method I'm using now, but, I'd still like a way to set a default rather than having to remember to `... + sfm`. Another reason I want this is because I would like to be able to share my code without sharing theming options. – Brandon Bertelsen Mar 30 '12 at 14:55
  • @BrandonBertelsen Sorry for duplicating what you already know! I agree this isn't optimal for the reasons you set out. I don't know of anything better, though. – joran Mar 30 '12 at 15:05
3

Changing the default palletes, can also be achieved by setting options, eg.:

options(ggplot2.continuous.colour="viridis")
options(ggplot2.continuous.fill="viridis")

If you have defined a custom scale, say scale_color_custom, you would need to change the options as follows:

options(ggplot2.continuous.colour=scale_color_custom)

Notice that you are feeding the options a raw function and not a string. The string "viridis" is a reserved special input, but using a function is more generic.

jan-glx
  • 7,611
  • 2
  • 43
  • 63