R:布局保存为png

时间:2013-02-21 13:02:44

标签: r

我有四个图表(类型:ggplot2),我试图将它们保存为png。但是,当我运行下面的代码时,只有ch4被保存。

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

我很想知道我做错了什么。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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()
相关问题