Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom ggplot2 function that combines theme and color

Tags:

r

ggplot2

I am often using the theme_hc() theme (from the package ggthemes) in ggplot2 graphs, combined with scale_colour_pander() or scale_fill_pander(). I want to make a custom function now called myTheme that combines these three functions into one.

I tried the following

myTheme <- function(){
  theme_hc() + scale_colour_pander() + scale_fill_pander()
}
data <- data.frame(x=1:2,y=3:4)
ggplot(data, aes(x=x, y=y)) + geom_point() + myTheme()

But apparently R evaluates this first inside the function and gives an error: 'Error: Don't know how to add scale_colour_pander() to a theme object'.

Then I tried

myTheme <- function(){
  ggplot() + theme_hc() + scale_colour_pander() + scale_fill_pander()
}
data <- data.frame(x=1:2,y=3:4)
ggplot(data, aes(x=x, y=y)) + geom_point() + myTheme()

Which returns: 'Error: Don't know how to add o to a plot'

Is there a way to achieve the desired effect or should I keep combining the individual commands?

like image 766
takje Avatar asked Jan 06 '16 09:01

takje


1 Answers

the standard technique is to wrap those elements in a list,

p + list( theme_hc() , scale_colour_pander() , scale_fill_pander())
like image 57
baptiste Avatar answered Nov 16 '22 10:11

baptiste