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

时间:2015-10-04 17:52:02

标签: r ggplot2 data-visualization

将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”中,我会收到错误Error: No layers in plot。什么是在单个对象中存储ggplot的所有元素(减去变量/数据)的更好方法?

谢谢。

1 个答案:

答案 0 :(得分:5)

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

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