ggplot2: Use options for multiple plots

2019-02-18 21:30发布

I would like to create 10 plots that have different data, but the same optical appearance. As an example, I’d like to change the colour of the gridline for each plot. This could be done by adding

+ opts(panel.grid.major = theme_line(colour = "white")

to each plot definition. However, when I now decide to change background colour to let’s say “grey25”, I’d have to modify each plot individually. This seems like way too much work. ;)

So, I thought about doing something like

opt1 <- '+ opts(panel.grid.major = theme_line(colour = "white")'

and then define each plot like

pl_x <- pl_x + opt1
pl_y <- pl_y + opt1
...

Other options (margins, fonts, scales,…) could then be added to opt1. However, that doesn’t work (error message when trying to print pl_x). Anybody maybe knows how to accomplish what I’d like to do?

I also played around with theme_set and theme_update, but that resulted in none off my plots working anymore unless I completely restarted R.

1条回答
趁早两清
2楼-- · 2019-02-18 22:12

You don't have to add the + sign.

opt <- opts(panel.grid.major = theme_line(colour = "white"))

pl_x <- pl_x + opt

Although this doesn't work:

opt <- opts(...) + scale_y_continuous(..)

This does:

opt <- opts(...)
syc <- scale_y_continuous(...)
pl_x <- pl_x + opt + syc

And thanks to Hadley's example, this works too:

opt <- list(opts(...),scale_y_continuous(...))

Note: Since version 0.9.2 opts has been replace by theme.

查看更多
登录 后发表回答