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

Reputation: 19375

how to print a list-column of ggplots to pdf?

Consider this funny example

mydata <- data_frame(group = c('a', 'a', 'a', 'b', 'b', 'b'),
           x = c(1,2,3,5,6,7),
           y = c(3,5,6,4,3,2))

> mydata
# A tibble: 6 x 3
  group     x     y
  <chr> <dbl> <dbl>
1 a         1     3
2 a         2     5
3 a         3     6
4 b         5     4
5 b         6     3
6 b         7     2

Here I can nest() by group, and store a group-based ggplot into a list-column. Crazy stuff.

> mydata %>% group_by(group) %>% 
+   nest() %>% 
+   mutate(myplot = map(data, ~ggplot(data = .x, aes(x = x, y = x)) + geom_point()))
# A tibble: 2 x 3
  group data             myplot  
  <chr> <list>           <list>  
1 a     <tibble [3 x 2]> <S3: gg>
2 b     <tibble [3 x 2]> <S3: gg>

However, I would like to use map to print each of these charts into a single pdf. That is, one pdf page per group.

Here I am at a loss. How can I do that? Thanks!

Upvotes: 0

Views: 875

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47320

Just open the pdf device and print them :)

library(tidyverse)
mydata <- data_frame(group = c('a', 'a', 'a', 'b', 'b', 'b'),
                     x = c(1,2,3,5,6,7),
                     y = c(3,5,6,4,3,2))

mydata2 <- mydata %>% group_by(group) %>% 
  nest() %>% 
  mutate(myplot = map(data, ~ggplot(data = .x, aes(x = x, y = x)) + geom_point()))

pdf()
print(mydata2$myplot)
dev.off()

As @aosmith comments you can skip the print call if you're using R interactively, but be careful that if you wrap it later into a function it won't work anymore, so I'd recommend to keep it explicit.

If you want to chain it :

pdf()
mydata %>% group_by(group) %>% 
  nest() %>% 
  mutate(myplot = map(data, ~ggplot(data = .x, aes(x = x, y = x)) + geom_point())) %>%
  pull(myplot) %>%
  print
dev.off()

The first argument of pdf is the path of your printed file and by default it's "Rplots.pdf", so it will be in your working folder. See ?pdf for more.

Upvotes: 2

Related Questions