radi
radi

Reputation: 3

Reset graph at the end of the loop :could not find function "device" error

I am trying to generate plots by looping, here is my code:

n <- unique(wide_data$Product.Code)[1:3]

for (i in n)

{


my.prod2 <- filter(tall_bind, Product.Code == i, Date > ymd("2012/04/01"))

dev.new()

mypath <- file.path("C:","R","SAVEHERE",paste("myplot_", i, ".jpg", sep = ""))

jpeg(file=mypath)

mytitle = paste("Plot for product", i)

p <- qplot(Date, Sold, data = my.prod2, geom = "line", main=mytitle, group = Model, colour = Model) + facet_grid(Model ~ .)

ggsave("myplot_", i, plot=p, device= "jpg" )

}

I get the following error for the above code:

Saving 6.67 x 6.67 in image

Error in ggsave("myplot_", i, plot = p, device = "jpg") : could not find function "device"

Earlier when I used dev.off() at the end of the loop, I found that though the graphs were being generated they were totally blank.

Could someone please help me understand where is the mistake in my code?

Upvotes: 0

Views: 1849

Answers (1)

ROLO
ROLO

Reputation: 4223

You can leave out the dev.new() and jpg() commands, and also your arguments to ggsave() are incorrect. This should work:

n <- unique(wide_data$Product.Code)[1:3]
for (i in n) {
    my.prod2 <- filter(tall_bind, Product.Code == i, Date > ymd("2012/04/01"))
    mypath <- file.path("C:","R","SAVEHERE",paste("myplot_", i, ".jpg", sep = ""))
    mytitle = paste("Plot for product", i)
    p <- qplot(Date, Sold, data = my.prod2, geom = "line", main=mytitle, group = Model, colour = Model) + facet_grid(Model ~ .)
    ggsave(filename = mypath, plot = p)
}

What you did was creating a new default graphics device, typically a plotting window, then a jpeg graphics device, i.e. a file. Then you tried to make ggplot2 to plot to directly to file using ggsave, i.e. using its own (jpg) device, and not using either of the two graphics devices you created.

The error, however, was because you gave ggsave the wrong arguments. But even with the right arguments, you would still have ended up with additional unused graphics windows and files through the dev.new() and jpeg() commands. I suggest some extra reading of the help (e.g. type ?ggsave at the r console).

Typically, when using ggplot2 you do not need to worry about dev.new, jpeg and the like. qplot or ggplot and ggsave should do all you need.

Upvotes: 1

Related Questions