2017-04-26 81 views
0

我想並排繪製兩個圖並將它們保存到文件。以下是我的代碼如下。問題是我無法控制利潤率。無論我輸入什麼保證金,它們都不會反映在文件中。輸出多個圖R到文件

一般來說,有關於如何在R中很好地打印文件的任何教程。我正在閱讀所有手冊和示例,但它不太清楚。當我打印時,事情變得非常有趣,我不記得在Matlab或Python中遇到過同樣的麻煩。 R具有自由度的音調。

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() 
+0

您是否嘗試設置邊距_before_您繪製圖表? – G5W

+0

@ G5W,我試過了,它不起作用。如果使用簡單的'plot'命令替換'grid.arrange',保證金似乎可以正常工作 – user1700890

回答

1

您可以使用cowplot包。主題函數中的plot.margin允許設置邊距。以下是四邊各有2釐米邊距的示例:

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() 
+0

非常感謝。現在,我不知道是否可以調整我的情節軸的大小,它現在看起來很醜陋 – user1700890

+1

不客氣。如果我們給出合理的論據,醜陋的,就像統計數據一樣客觀。也就是說,打開另一個問題可能是獲得關於調整軸的問題的答案的最佳方式。 – dca