user3789200
user3789200

Reputation: 1186

Multiple plot in R in a single page

I'm having trouble displaying the multiple graphs on the same page. I'm having a data frame with 18 numerical columns. For each column, I need to show its histogram and boxplot on the same page with a 4*9 grid. Following is what I tried. But I need to show it along with the boxplot as well. Through a for a loop if possible. Can someone please help me to do it.

library(gridExtra)
library(ggplot2)
p <- list()
for(i in 1:18){
  x <- my_data[,i]
  p[[i]] <-   ggplot(gather(x), aes(value)) + 
    geom_histogram(bins = 10) + 
    facet_wrap(~key, scales = 'free_x')
}
do.call(grid.arrange,p)

I received the following graph. enter image description here

When following is tried, I'm getting the graph in separate pages

library(dplyr)

dat2 <- my_data %>% mutate_all(scale)

# Boxplot from the R trees dataset
boxplot(dat2, col = rainbow(ncol(dat2)))


par(mfrow = c(2, 2))  # Set up a 2 x 2 plotting space
# Create the loop.vector (all the columns)
loop.vector <- 1:4
p <- list()
for (i in loop.vector) { # Loop over loop.vector
  
  # store data in column.i as x
  x <- my_data[,i]
  
  # Plot histogram of x
  p[[i]] <-hist(x,
       main = paste("Question", i),
       xlab = "Scores",
       xlim = c(0, 100))
  
  plot_grid(p, label_size = 12)
}

Upvotes: 0

Views: 202

Answers (1)

mt1022
mt1022

Reputation: 17319

You can assemble the base R boxplot and the ggplot object generated with facet_wrap together using the R package patchwork:

library(ggplot2)
library(patchwork)

p <- ggplot(mtcars, aes(x = mpg)) +
    geom_histogram() +
    facet_wrap(~gear)

wrap_elements(~boxplot(split(mtcars$mpg, mtcars$gear))) / p
ggsave('test.png', width = 6, height = 8, units = 'in')

enter image description here

Upvotes: 1

Related Questions