ggplot facet_wrap_paginate pages grouped by variable

902 Views Asked by At

I'm working on creating some harvest plots for a paper and am stumbling a bit with the code. I have recreated the important bits using 'diamonds' so that it's easier for people to recreate

Part 1

The aim is to create a bar chart that will facet by multiple variables, e.g. 'carat' and 'color', as these will act as the titles for the plots. I've used ggforce's paginate to allow me to spread it over multiple pages, as I'd like each page to show results by a group - here I've added values '1', '2', or '3' to each row of the dataframe. Whilst I could subset the dataframe and create the plots individually, the issue is that the widths of the bars aren't consistent between pages, even when I add width = x to geom_bar (though the widths are the same within each page).

Does anyone have an idea of how I can accomplish this? I was wondering if aes_string would help, but wasn't sure it'd work with the multiple facets I need.

Part 2 When I try and add in some code to save the images it overrides the grid.arrange ... command to specify plot size (so they are all consistent) and adjusts to fill the white space. Is this easily fixed?

Thanks, Cal

library(ggplot2)
library(ggforce)
library(plyr)
library(dplyr)
library(grid)
library(egg)

df = diamonds
df$Group<- rep(1:3,length.out=nrow(df))

for (i in df$Group) {

  p <- ggplot(data=df, aes(x=cut, y=clarity, fill=price)) +
    # preserve = single keeps all bars same width, rather than adjusting to 
    # the space
    geom_bar(position=position_dodge2(preserve = 'single'),
             stat="identity", color = "black", size = 0.2) + 
    # paginate allows the chart to be printed on multiple pages
    # strip position adds facet title to top of page
    facet_wrap_paginate(c("carat","color"), ncol = 3, nrow = 3,
                        scales = "fixed", strip.position = "top", page = i)


  # manually adjust the size of the plot panels
  grid.arrange(grobs = lapply(
    list(p),
    set_panel_size,
    width = unit(8,"cm"),
    height = unit(5,"cm")
  ))
}
0

There are 0 best solutions below