user1700890
user1700890

Reputation: 7730

Output multiple plots to file in R

I am trying to plot two graphs side by side and save them to file. Here is my code below. The problem is that I cannot control margins. Whatever margin I enter, they are not reflected in the file.

In general is there any tutorial on how to print nicely to file in R. I am reading through all manuals and examples, but it is not too clear. When I print, things are getting distorted in very interesting fashion, I do not recall having same trouble in Matlab or Python. R has tones of degrees of freedom.

library(ggplot2)
library(gridExtra)

sample_df <- data.frame(col_1=c(1,2,3), col_2=c(6,7,8))
plot_1 <-ggplot(data=sample_df, aes(x = col_1, y =col_2, group=1))+
  geom_line()+ggtitle('Title 1')
plot_2 <-ggplot(data=sample_df, aes(x = col_1, y =col_2, group=1))+
  geom_line()+ggtitle('Title 2')

width_letter = 6
height_letter = width_letter*8.5/11

pdf('outpdf_1.pdf', width=width_letter, height=height_letter)
par(mai=c(3.02,0.82,0.82,0.42))
grid.arrange(plot_1, plot_2, ncol=2)
dev.off()

Upvotes: 0

Views: 624

Answers (1)

dca
dca

Reputation: 652

You can use the cowplot package. The plot.margin inside of the theme function allows margins to be set. Here's an example with 2cm margins on each of the four sides:

library(ggplot2)
library(gridExtra)
library(cowplot)

sample_df <- data.frame(col_1=c(1,2,3), col_2=c(6,7,8))
plot_1 <-ggplot(data=sample_df, aes(x = col_1, y =col_2, group=1))+
  geom_line()+ggtitle('Title 1')
plot_2 <-ggplot(data=sample_df, aes(x = col_1, y =col_2, group=1))+
geom_line()+ggtitle('Title 2')

width_letter = 6
height_letter = width_letter*8.5/11

pdf('outpdf_1.pdf', width=width_letter, height=height_letter)
plot_grid(plot_1, plot_2, labels = "AUTO", ncol = 2, align = 'v') +   
 theme(plot.margin = unit(c(2,2,2,2), "cm")) 

dev.off()

Upvotes: 1

Related Questions