gpt4 book ai didi

r - 在对象中存储自定义 ggplot 样式

转载 作者:行者123 更新时间:2023-12-02 02:40:21 26 4
gpt4 key购买 nike

将 ggplot 样式保存到 R 中的对象的最佳方法是什么?我知道 ggplot 有自定义主题,但有很多视觉设计不适合主题功能。

这是我一直在研究的一些示例(融化的)数据和图表

library(ggplot2)

mdf <- structure(list(group = structure(c(2L, 3L, 1L, 2L, 3L, 1L), .Label = c("democrat",
"founder", "libertarian"), class = "factor"), variable = structure(c(1L,
1L, 1L, 2L, 2L, 2L), .Label = c("similar", "compete"), class = "factor"),
value = c(0.7, 0.2, 0.4, 0.3, 0.8, 0.6)), row.names = c(NA,
-6L), .Names = c("group", "variable", "value"), class = "data.frame")

ggplot(mdf, aes (x=group, y=value, fill = variable)) +
geom_bar(stat="identity", position="dodge", alpha = 0.8) +
geom_bar(stat="identity", position="dodge", color = "#A9A9A9", alpha = 0.8) +
scale_fill_manual(values=c("#05f2ae", "#17b0c4")) +
geom_text(aes(x=group, y=value, ymax=value, label=value),
position=position_dodge(1), vjust=-1, size=12) +
coord_cartesian(ylim = c(0, 1))
theme(plot.margin = unit(c(1,1,2,2), "cm"),
axis.text.x = element_text(vjust=0.5, size=20),
plot.title=element_text(size=20, vjust=2),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
axis.title.x = element_blank(), axis.title.y = element_blank(),
panel.background = element_rect(fill = "#D9D9D9"))

我正在生成许多具有相同设计的图表,并且希望将设计存储在单个对象中,例如“plot_style”,以便图表会自动更新为样式,即使我决定稍后更改它。

如果我尝试将 ggplot(...) 下面的所有内容存储在对象“x”中,则会收到错误,错误:图中没有图层。将 ggplot 的所有元素(减去变量/数据)存储在单个对象中的更好方法是什么?

谢谢。

最佳答案

您可以创建自定义列表,然后将其应用到每个绘图。例如:

customPlot = list(
theme(plot.margin = unit(c(1,1,2,2), "cm"),
axis.text.x = element_text(vjust=0.5, size=20),
plot.title=element_text(size=20, vjust=2),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
axis.title.x = element_blank(), axis.title.y = element_blank(),
panel.background = element_rect(fill = "#D9D9D9")),
coord_cartesian(ylim = c(0, 1)),
scale_fill_manual(values=c("#05f2ae", "#17b0c4"))
)

ggplot(mdf, aes (x=group, y=value, fill = variable)) +
geom_bar(stat="identity", position="dodge", alpha = 0.8) +
geom_bar(stat="identity", position="dodge", color = "#A9A9A9", alpha = 0.8) +
geom_text(aes(x=group, y=value, ymax=value, label=value),
position=position_dodge(1), vjust=-1, size=12) +
customPlot

关于r - 在对象中存储自定义 ggplot 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32936506/

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