0

I can use ggplot2 to store the output of ggplot command to an object and call that object within grid.arrange to write to a file in an R script, as below:

p<-ggplot(x, aes(x=Date, y=Date)) + geom_bar(aes(x=Date,y=Data)

png("data.png", height=700, width=650)

grid.arrange(p, main=textGrob("Data"), gp=gpar(cex=2)               

dev.off()

I am creating bunch of forecast graphs using plot but I cannot do the same thing. Any one has any suggestion how can I write the ouput of plot to a png file in a script?

4

2 回答 2

4

We don't have data to work with and the questions not clear so here's an example of what I think the OP is after (separate plots for each plot) using the mtcars data set:

dat <- split(mtcars, mtcars$cyl)

lapply(dat, function(x) {
    ggplot(x, aes(mpg, disp, colour=gear)) + geom_point()
    }
)

#a way to get separate plots for each plot
plot2 <- function(theplot, name, ...) {
    name <- paste0(name, ".png")
    png(filename=name)
    print(theplot)
    dev.off()
} #plotting function

lapply(seq_along(dat), function(i) {
    x <- dat[[i]]
    z <- ggplot(x, aes(mpg, disp, colour=gear)) + geom_point()
    plot2(z, name=paste0("TEST", names(dat)[i]))
    }
)
于 2012-08-03T17:55:03.173 回答
0
data <- data.frame(x=1:10,y=rnorm(10))
p <- ggplot(data, aes(x,y)) + geom_point()
p
library(gridExtra)
Loading required package: grid
grid.arrange(p,p,p)
ggsave('~/Desktop/grid.png')

Does this approach not work with forecast graphs?

于 2012-08-03T17:27:32.860 回答