在分析工作中,我使用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>
答案 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()
通话结束时您使用了分号。不确定为什么会出现分号...)