如何创建要插入ggplot的对象(当带有+的多个部分时)?

时间:2018-10-02 00:13:55

标签: r ggplot2

在分析工作中,我使用ggplot中的R来绘制多个图。我想将所需的绘图主题(使用ggtheme加上一些手动更改)设置为单个对象,然后在我生成的每个绘图中调用此主题。我在下面举了一个例子。

由于主题对象的定义中存在+,因此此代码引发错误。 ggplot函数将此符号识别为添加了新元素,但是在创建单独的THEME对象以调用ggplot时,我无法使用该符号。显然,我可以将主要主题转移到ggplot调用中,而将我的手动更改保留在THEME中,但是为了简洁起见,我希望将整个内容放在一个对象中。

#Load libraries
library(ggplot2);
library(ggthemes);

#Create mock data for illustrative purposes
DATA <- data.frame(x = c(3,6,8,11,2,7,4,4,3,6),
                   y = c(12,8,8,4,15,10,9,13,11,6));

#Set theme for plots
THEME <- theme_economist() + scale_colour_economist() +
         theme(plot.title    = element_text(hjust = 0.5),
               plot.subtitle = element_text(hjust = 0.5, face = 'bold'),
               axis.title.y  = element_text(face = 'bold', size = 12),
               plot.margin        = margin(t = 0, r = 20, b = 0));

#Error: Don't know how to add RHS to a theme object

#Generate plot using above theme
FIGURE <- ggplot(data = DATA, aes(x = x, y = y)) +
          geom_point() + THEME;
FIGURE;

问题::如何修改THEME的定义,以允许我指定主题和更改在单个对象中可以稍后在ggplot中调用?< / p>

1 个答案:

答案 0 :(得分:2)

list包裹主题调用,并用逗号替换+:

THEME <- list(theme_economist(), scale_colour_economist(),
         theme(plot.title    = element_text(hjust = 0.5),
               plot.subtitle = element_text(hjust = 0.5, face = 'bold'),
               axis.title.y  = element_text(face = 'bold', size = 12),
               plot.margin        = margin(t = 0, r = 20, b = 0)))

(请注意,theme()通话结束时您使用了分号。不确定为什么会出现分号...)