Home > Mobile >  Stacking multiple figures together in ggplot
Stacking multiple figures together in ggplot

Time:01-19

I am attempting to make publication ready figures where the bottom axis (with tick marks) of one figure is cleanly combined with the top axis of the figure below it. Here is an example of what it might look like, although this one doesn't have tick marks on each panel:

enter image description here

Here is my attempt to do so, by simply using grid.arrange:


#Libraries:

library(ggplot2)
library(dplyr)
library(gridExtra)

#Filter to create two separate data sets:

dna1 <- DNase %>% filter(Run == 1)
dna2 <- DNase %>% filter(Run == 2)

#Figure 1:

dna1_plot <- ggplot(dna1, aes(x = conc, y = density))   geom_point()   theme_classic()   
  theme(axis.title.x = element_blank())

#Figure 2: 

dna2_plot <- ggplot(dna2, aes(x = conc, y = density))   geom_point()   theme_classic() 

#Using grid.arrange to combine:

dna <- grid.arrange(dna1_plot, dna2_plot, nrow = 2)

enter image description here

And an attempt with some adjustments to the plot margins, although this didn't seem to work:


dna1_plot_round2 <- ggplot(dna1, aes(x = conc, y = density))   geom_point()   theme_classic()   
  theme(axis.title.x = element_blank(), 
        plot.margin = (0,0,0,0), "cm")

dna2_plot_round2 <- ggplot(dna2, aes(x = conc, y = density))   geom_point()   theme_classic()  
  theme(plot.margin = unit(c(-0.5,-1,0,0), "cm"))

dna_round2 <- grid.arrange(dna1_plot_round2, dna2_plot_round2, nrow = 2)

enter image description here

Does anyone know the best way to stack figures like this in ggplot? Is there a better way than using grid.arrange? If possible it would be great to see how to do it with/without tick marks on each x axis as well.

Thank you!

CodePudding user response:

You don't need any non-native ggplot stuff. Keep your data in one data frame and use facet_grid.

dna <- DNase %>% filter(Run %in% 1:2)

ggplot(dna, aes(x = conc, y = density))   
  geom_point()   
  theme_bw()   
  facet_grid(rows = vars(Run))

enter image description here

CodePudding user response:

The R package enter image description here

  •  Tags:  
  • Related