2013-02-21 96 views
1

我有四個圖表(類型:ggplot2),並試圖將它們保存爲PNG。但是,當我運行下面的代碼時,只有ch4被保存。R:佈局保存爲PNG

png(filename = fname, width = 900, height = 600, units = 'px') 
layout(matrix(c(1,2,3,4), 2, 2, byrow = TRUE)) 
ch1 
ch2 
ch3 
ch4 
dev.off() 

我將不勝感激,知道我在做什麼錯。

+0

也許你應該在調用png()之前進行佈局? – jrara 2013-02-21 13:03:35

+2

如果他們是ggplot2圖,你可能需要從'gridExtra'包中嘗試'grid.arrange()',我不認爲基礎佈局函數有效。 – Marius 2013-02-21 13:06:08

+0

adam.888,'ggplot'函數會覆蓋任何佈局或視口規範,所以您沒有看到的是這些'ggplot'命令中的每一個都在使用整個頁面並覆蓋以前的圖表。 – Dinre 2013-02-21 13:29:50

回答

2

GGPLOT2圖形可以使用grid.arrange()gridExtra封裝在一個頁面上奠定了,如:

df <- data.frame(x=1:3, y=c(1, 4, 9)) 
p <- ggplot(df, aes(x, y)) 
p1 <- p + geom_point(colour="red") 
p2 <- p + geom_point(colour="blue") 
p3 <- p + geom_point(colour="green") 
p4 <- p + geom_point(colour="purple") 

library(gridExtra) 
png(filename="test.png", width=600, height=600) 
grid.arrange(p1, p2, p3, p4) 
dev.off() 
+0

啊,很好。我開始懷疑有人會將你的評論打包成適當的答案。 'grid.arrange'函數絕對是在這裏使用的函數,因爲否則無法爲'ggplot'函數指定視口。 – Dinre 2013-02-21 13:26:57

+0

非常感謝你。 – 2013-02-21 14:31:30

2

使用grid.arrange代替layout

library(ggplot2) 
library(gridExtra) 
ch1 <- qplot(1,2) 
ch2 <- qplot(1,2) 
ch3 <- qplot(1,2) 
ch4 <- qplot(1,2) 

png(filename = "fname.png", width = 900, height = 600, units = 'px') 
grid.arrange(ch1,ch2,ch3,ch4, ncol = 2) 
dev.off() 

enter image description here

你可以使用基地的基礎繪圖layout功能。需要注意的是,文件擴展名必須內部""到指定:

png(filename = "fname.png", width = 900, height = 600, units = 'px') 
layout(matrix(c(1,2,3,4), 2, 2, byrow = TRUE)) 
plot(1,2) 
plot(1,2) 
plot(1,2) 
plot(1,2) 
dev.off() 

enter image description here

+0

使用變量來指定文件名不是問題。我一直這麼做。 – Dinre 2013-02-21 13:25:42

+0

恩,(類型:ggplot2)在我寫第一個答案後(或者我至少沒有看到)添加。我相應地編輯了我的答案。 – Mikko 2013-02-21 13:25:48

+0

如果你放棄了'fname'是問題的堅持,你的答案會很有幫助。該操作說明輸出正在生成,但只有最後一個圖表被寫入PNG文件。一個PNG文件顯然正在輸出,所以'fname'不需要修改。 – Dinre 2013-02-21 13:35:37