Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store custom ggplot styles in object

What is the best way to save a ggplot style to an object in R? I know ggplot has custom themes, but there's a lot of visual designs that don't fit into theme function.

Here's some sample (melted) data and a graph I've been working on

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")) 

I'm producing a lot graphs with the same design and want to store the design in a single object, like "plot_style", so that the graphs are automatically updated with the style, even if i decide to change it later.

If I try to store everything below ggplot(...) in an object "x", I get an error, Error: No layers in plot. What is better way to store all of the elements of a ggplot (minus the variables/data) in single object?

Thank you.

like image 606
tom Avatar asked Oct 04 '15 17:10

tom


1 Answers

You can create a list of customizations and then apply that to each plot. For example:

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
like image 198
eipi10 Avatar answered Nov 08 '22 09:11

eipi10