how to change the height/weight in a ggplot printe

2019-09-03 14:24发布

问题:

Consider this list of ggplots:

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)) %>% 
  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>

I can print the plots contained in myplot using the simple:

pdf('P://mychart.pdf')
do.call("grid.arrange", c(mydata $myplot))
dev.off()

However, the charts are all contained in a square, wasting a lot of space on the margin. How can I get control over the margins here so that the charts are all wider?

Thanks!

回答1:

You can use ggsave:

ggsave("P://mychart.pdf", do.call("arrangeGrob", mydata$myplot), 
  width = 9, height = 6, units = "in")

The plot as seen above is a .png, but ggsave works perfectly with .pdf.


If you instead want to plot every item in the myplot list as single .pdf files, you could use mapply:

mapply(function(x, y){
  ggsave(paste0("P://mychart", x, ".pdf"), y, width = 9, height = 6, units = "in")
},1:length(mydata$myplot), mydata$myplot)

This will produce to plots, mychart1.pdf and mychart2.pdf.



标签: r ggplot2