Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are good ways to preset plotting options for ggplot in R

Tags:

r

ggplot2

Im having a bunch of lengthy repetitive ggplot2 instructions throughout a file. So far i've been using variables control preset values keeping graphs uniform, having the configuration in one spot (e.g. to change the color of all graphs).

What i'm really looking for is a good way to preset those instructions so i don't have to write the statements all over. As an example, i define somewhere top in the file:

OPTAX=theme_text(angle=30, hjust=1, vjust=1, size=8)

Where the plot statements is, i use

P<-ggplot(
       data=MYDATA,
       aes(x=Topics, y=value, fill=variable)) +
       ....
       opts(axis.text.x=OPTAX)
)

I would like to avoid writing the axis.text.x=MYVAR part and write something like

... + opts(MYOPTS) + ...

or avoid the opts statement at all and write

... + ALLMYOPTS + ...

so all my options are predefined in one statement.

As a second thing it would be good to override the statement. Something like

opts(MYOPTS, axis.text.x=theme_text(angle=60)

would be great, so i can keep the preset but still use custom options.

like image 879
count0 Avatar asked Aug 30 '12 16:08

count0


3 Answers

You can wrap up all sorts of ggplot configuration - not just opts - and apply it to multiple graphs, by using a list:

myPrettyOptions = list(
   opts(axis.text.x=OPTAX),
   facet_wrap(~Topic),
   limits(x=c(1,2)),
   scale_x_discrete(expand=c(0,0,5))
)

Then use this in multiple locations: (think of the space you will save!):

ggplot(blah) + myPrettyOptions
# in the second plot we can override the options:
ggplot(foo) + myPrettyOptions + opts(axis.text.x=theme_text(angle=60)

You can take this even further and prepare everything except the data:

graphtemplate = ggplot(blah) + myPrettyOptions
graphtemplate %+% data1
graphtemplate %+% data2

Note the use of the %+% operator.

like image 191
Alex Brown Avatar answered Nov 09 '22 10:11

Alex Brown


An even more terse approach involves using the theme_update, theme_get, and theme_set methods.

old.theme <- theme_update(axis.text.x = theme_text(angle=30, hjust=1, vjust=1, size=8))
qplot(1,1)

If you want to revert to the old theme use, simply,

theme_set(old.theme)
qplot(1,1)
like image 38
ppham27 Avatar answered Nov 09 '22 08:11

ppham27


This will work:

ALLMYOPTS <- opts(axis.text.x = theme_text(angle=30, hjust=1, vjust=1, size=8))
P + ALLMYOPTS
like image 44
David LeBauer Avatar answered Nov 09 '22 09:11

David LeBauer