gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:22:35 25 4
gpt4 key购买 nike

在我的分析工作中,我使用 R 中的 ggplot 来生成多个图。我想将我想要的情节主题(使用 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 中调用?

最佳答案

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() 调用的末尾有一个分号。不确定为什么会出现...)

关于r - 如何创建要插入到 ggplot 中的对象(当有多个带 + 的部分时)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52600483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com