adam.888
adam.888

Reputation: 7846

R: layout saving as png

I have four charts (type: ggplot2)and am trying to save them as a png. However when I run the code below only ch4 gets saved.

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

I would be grateful to know what I am doing wrong.

Upvotes: 1

Views: 1840

Answers (2)

Mikko
Mikko

Reputation: 7775

Use grid.arrange instead of 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

You could use layout function for base base plotting. Note that the file extension has to be specified inside "":

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

Upvotes: 2

Marius
Marius

Reputation: 60230

ggplot2 graphs can be layed out on a single page using grid.arrange() from the gridExtra package, e.g.:

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

Upvotes: 2

Related Questions