Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autoplot saves blank plot to png device when chained within data.table

I have a data.table with a column with forecasts of some values, and I want to save plots of each of those forecasts with ggplot2::autoplot.

I'm attempting this (reproducible example):

require(data.table)
require(forecast)
require(ggplot2)

## create data.table
a <- data.table(id = 1:2)
a[, x := .(list(sample(1:10, 5, FALSE))), by = id]
a[, y := .(list(forecast(x[[1]]))), by = id]

## plot by id:
a[, {png(paste0(id, ".png")); autoplot(y[[1]]); dev.off()}, by = id]

but it creates blank canvases.

However, the following code works:

png("1.png")
a[1, autoplot(y[[1]])]
dev.off()

Which makes me think that it's something with the chaining of commands inside the {}. The next code also works (since plot doesn't work with forecast objects, I'm plotting the x variable:

a[, {png(paste0(id, ".png")); plot([[1]]); dev.off()}, by = id]

which makes me think of autoplot.

What am I doing wrong, and what would be the way to effectively achieve what I want?

like image 688
PavoDive Avatar asked Nov 16 '25 18:11

PavoDive


1 Answers

Without looking into autoplot code, the difference between those two expressions is a hidden print which happens in the 2nd case, since that expression returns the object created by autoplot, which then R core "prints" (which can mean different things for different objects).

Thus the fix is in calling print yourself:

a[, {png(paste0(id, ".png")); print(autoplot(y[[1]])); dev.off()}, by = id]
like image 122
eddi Avatar answered Nov 18 '25 07:11

eddi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!