如何将ggplots的列表列打印为pdf? [英] how to print a list-column of ggplots to pdf?
问题描述
考虑以下 funny
示例
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
在这里,我可以按组进行 nest()
,并将基于组的 ggplot
存储到 list-column
中.疯狂的事情.
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>
但是,我想使用 map
将每个图表打印到单个 pdf
中.也就是说,每组一页 pdf
.
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!
推荐答案
只需打开pdf设备并打印:)
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()
作为@aosmith的注释,如果以交互方式使用R,则可以跳过打印调用,但是要小心,如果以后将其包装到一个函数中将不再起作用,因此,我建议将其保持明确.
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.
如果要链接它:
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()
pdf
的第一个参数是打印文件的路径,默认情况下为"Rplots.pdf"
,因此它将位于您的工作文件夹中.有关更多信息,请参见?pdf
.
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.
这篇关于如何将ggplots的列表列打印为pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!