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.
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.
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)
This will work:
ALLMYOPTS <- opts(axis.text.x = theme_text(angle=30, hjust=1, vjust=1, size=8))
P + ALLMYOPTS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With