简体   繁体   English

创建结合主题和颜色的自定义ggplot2函数

[英]Create custom ggplot2 function that combines theme and color

I am often using the theme_hc() theme (from the package ggthemes) in ggplot2 graphs, combined with scale_colour_pander() or scale_fill_pander(). 我经常在ggplot2图中使用theme_hc()主题(来自包ggthemes),结合scale_colour_pander()或scale_fill_pander()。 I want to make a custom function now called myTheme that combines these three functions into one. 我想创建一个名为myTheme的自定义函数,它将这三个函数合二为一。

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'. 但显然R首先在函数内部对此进行求值并给出错误:'错误:不知道如何将scale_colour_pander()添加到主题对象'。

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' 返回:'错误:不知道如何将o添加到图中'

Is there a way to achieve the desired effect or should I keep combining the individual commands? 有没有办法达到预期的效果,还是应该继续组合各个命令?

标准技术是将这些元素包装在列表中,

p + list( theme_hc() , scale_colour_pander() , scale_fill_pander())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM