LeMarque
LeMarque

Reputation: 783

Create a three panel plot with one panel spanning 2 columns using ggplot2

I have following data:

    df <- data.frame("Stat" = c("Var1","Var1","Var1","Var1","Var1","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var3","Var3","Var3","Var3","Var3","Var3","Var3","Var3","Var3","Var3"),

"Value" = c(0,1,2,3,4,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,10),

"n" = c(33,120,223,63,20,17,28,33,22, 35,41,53,44,55,59,39,33, 46,30,29,23,21,14,6,18,7,29,50,80,86,91,83,35,34, 20))

What I wanted to do is to plot the above data as bar plot in one canvas but in three rows (1 columns x 3 rows) and each panel should contain plot for only one variable (Stat) eg. Var1 in first panel, Var2 in second and Var3 in the third panel, using the following code:

library(multipanelfigure)

fig1 <- multi_panel_figure(columns = 2, rows = 2, panel_label_type = "none")

# fit the plots on the panels
fig1 %<>%
  fill_panel(Var1Plot, column = 1, row = 1) %<>%
  fill_panel(Var2Plot, column = 2, row = 1) %<>%
  fill_panel(Var3Plot, column = 1:2, row = 2) 

fig1

Issue is how to get the Var1Plot, Var2Plot and Var3Plot so that these can be placed in respective panels above. I used the below code, but not able to get the results into above panels:

 library(tidyverse)
 df %>% ggplot(aes(x = Value, y = n)) +
  geom_bar(stat='identity') + facet_wrap(~ Stat)

Expected plot should look something like this :

enter image description here

Upvotes: 3

Views: 653

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24790

Here's an approach with cowplot.

library(cowplot)
figure.list <- map(unique(df$Stat), ~
  ggplot(data = subset(df, df$Stat == .x), aes(x = Value, y = n)) +
  geom_bar(stat='identity') + 
  ggtitle(.x))

top <- plot_grid(figure.list[[1]], figure.list[[2]], ncol = 2)
bottom <- plot_grid(figure.list[[3]], ncol = 1)
plot_grid(top, bottom,
          ncol=1, rel_heights=c(1,1))

enter image description here

If you really want some to be coord_flip-ed, you could make the list manually:

figure.list <- list()
figure.list[[1]] <- ggplot(data = subset(df, df$Stat == "Var1"), aes(x = Value, y = n)) +
  geom_bar(stat='identity') + coord_flip()
figure.list[[2]] <- ggplot(data = subset(df, df$Stat == "Var2"), aes(x = Value, y = n)) +
  geom_bar(stat='identity') + coord_flip()
figure.list[[3]] <- ggplot(data = subset(df, df$Stat == "Var3"), aes(x = Value, y = n)) +
  geom_bar(stat='identity')


top <- plot_grid(figure.list[[1]], figure.list[[2]], ncol = 2)
bottom <- plot_grid(figure.list[[3]], ncol = 1)
plot_grid(top, bottom,
          ncol=1, rel_heights=c(1,1))

enter image description here

Upvotes: 3

Related Questions