ℕʘʘḆḽḘ
ℕʘʘḆḽḘ

Reputation: 19395

how to fit multiple ggplot charts on a a4 pdf?

Consider this simple example

library(dplyr)
library(ggplot)
library(patchwork)

mytib <- tibble(group = as.factor(c(1,1,1,1,2,2,2,2,3,3,3,3)),
       y = c(1,2,3,42,50,400,3,3,2,3,3,4),
       x = c('a','b','c','d','a','b','c','d','a','b','c','d'))


p1 <- mytib %>% ggplot(aes(x = x, y = y, fill = group)) +
  geom_col() + ggtitle('this is a messy chart')+
  coord_flip()+
  xlab('Hello') +
  ylab('This is a nice comment')

Now I use patchwork to combine the charts so that I obtain 3 rows of 3 charts each on a regular a4 pdf page

(p1 + p1 + p1)/
(p1 + p1 + p1)/
(p1 + p1 + p1)

ggsave(file="a4_output.pdf", width = 210, height = 297, units = "mm")

enter image description here

The output is a nice a4 pdf but the problem is that the charts on the pdf are very stretched. Is there a way to preserve their original ratio (on the pdf) so that they look less stretched, even three on a single row? I dont mind if they look smaller.

Any ideas? Thanks!

Upvotes: 1

Views: 1643

Answers (1)

tjebo
tjebo

Reputation: 23767

The problem is the changing plot ratio. Now, coord_flip doesn't work with fixed ratio - but user Axeman explained how to deal with this problem - use ggstance!! I changed the plot mildly, using geom_colh, switched your x and y, and added a fixed ratio. Now we can use your plot layout, or simply pack the plots in a list and use wrap_plots. I did not use the reprex output because I am sharing the screenshot from the pdf output.

library(tidyverse)
library(patchwork)
library(ggstance)

mytib <- tibble(group = as.factor(c(1,1,1,1,2,2,2,2,3,3,3,3)),
                y = c(1,2,3,42,50,400,3,3,2,3,3,4),
                x = c('a','b','c','d','a','b','c','d','a','b','c','d'))

p1 <- 
  mytib %>% ggplot(aes(x = y, y = x, fill = group)) +
  geom_colh() + ggtitle('this is a messy chart')+
  coord_fixed(100)+
  xlab('Hello') +
  ylab('This is a nice comment')

plotlist <- list()
for(i in 1:9) { plotlist[[i]] <- p1 }

ggsave(plot = wrap_plots(plotlist), file="a4_output.pdf", width = 210, height = 297, units = "mm")

enter image description here

Another solution is to add another row - not with an empty plot, but using plot_layout

(p1 + p1 + p1)/
  (p1 + p1 + p1)/
  (p1 + p1 + p1) +
  plot_layout(nrow = 4)

Upvotes: 2

Related Questions