Search code examples
rplotlapplyxts

R How do save xts plots using lapply


I am working with some parliamentary text copra and I'm trying to visualize some of the results. Since I got a list of items I am trying to use a lapply to iterate through my list.

    keywords <- c("inburgering", 
             "inburgeringscursus", 
             "inburgeringsplicht", 
             "kennismigranten", 
             "gezinshereniging", 
             "gezinsvorming", 
             "Vreemdelingenwet")}

While outputting barplots works just fine

lapply(keywords, function(keyword){
  dt <- dispersion(corpus_in_use, query = keyword, sAttribute = "date")
  ts <- xts(x = dt[,count],
          order.by = as.Date(sprintf("%s-01-01", dt[["date"]])))
  ts_qtr <- aggregate(ts, as.Date(sprintf("%s-01-01", gsub("^(\\d{4})-.*?$", "\\1", index(ts)))))

  jpeg(
    filename = paste("/Users/simgeh/Downloads/bar_", keyword, ".jpg", sep=""),
    width = 2000, height = 1200,
    res = NA
  )

  barplot(ts_qtr, main=keyword, lwd=1, las=3)
  dev.off()
})

visualizing lineplots using plot won't work. I got no error. Just null device 1.

lapply(keywords, function(keyword){
  disp <- dispersion(corpus_in_use, query = keyword, sAttribute = c("date", "party"))
  ts <- xts(x = disp[,c("CDA", "PVV", "VVD", "PvdA", "D66", "GL")],
            order.by = as.Date(sprintf("%s-01-01", disp[["date"]])))

  #ts_adj <- aggregate(ts, as.Date(sprintf("%s-01-01", gsub("^(\\d{4})-.*?$", "\\1", index(ts)))))
  ts_adj <- as.xts(aggregate(ts, as.Date(as.yearmon(index(ts)))))

  jpeg(
    filename = paste("/Users/simgeh/Downloads/", keyword, ".jpg", sep=""),
    width = 4000, height = 2400,
    res = NA
  )

  plot(ts_adj, 
       main=keyword, 
       multi.panel = TRUE, 
       col = c("black", "black", "blue", "green", "red", "yellow"), 
       lwd=6, 
       cex = 1.5, 
       las = 1)
  dev.off()
})

Any help is appreciated.


Solution

  • I solved it. You have to set it in print:

    print(plot(ts_adj, 
           main=keyword, 
           multi.panel = TRUE, 
           col = c("black", "black", "blue", "green", "red", "yellow"), 
           lwd=6, 
           cex = 1.5, 
           las = 1))
      dev.off()