Home > Enterprise >  R: Saving JPEGS in R
R: Saving JPEGS in R

Time:10-24

I am working with the R programming language.

I have the following dataset:

library(treemap)
library(dplyr)

var1 <- c("A", "B", "C", "D", "E")
var1<- sample(var1, 1000, replace=TRUE, prob=c(0.2, 0.2, 0.2, 0.2, 0.2))
var1<- as.factor(var1)

var2 <- c("abc", "bcd", "egf", "hiu", "lkj", "oiu", "piu", "xsr", "zze", "tre")
var2<- sample(var2, 1000, replace=TRUE, prob=c(0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1))
var2<- as.factor(var2)

my_data = data.frame(var1, var2)

my_data = data.frame(my_data %>% group_by(var1, var2) %>% summarise(counts = n()))

I am now using this code to make a treemap for the entire dataset:

resize.win <- function(Width=6, Height=6)
{
        # works for windows
    dev.off(); # dev.new(width=6, height=6)
    windows(record=TRUE, width=Width, height=Height)
}

resize.win(10,10)
treemap(my_data, index = c("var1", "var2"), vSize = "counts", type = "index", palette = "Set1", title = "my map")

enter image description here

Now, I would like to make an individual treemap for each unique factor of var1 using a LOOP, and then save each of them. I tried to do this with a loop:

levs = my_data$var1
factors = lapply(levs[sapply(levs, is.factor)], levels)
factors = factors[[1]]

my_list = list()

for (i in 1:length(factors))

{

index_i = factors[[i]]

title_i = paste0("Tree Map", index_i)

data_i = my_data[which(my_data$var1 == index_i),]

treemap_i = treemap(data_i, index = c("var1", "var2"), vSize = "counts", type = "index", 

palette = "Set1", title = title_i)

my_list[[i]] = treemap_i

save_title_i = paste0("treemap_",i, ".png")

 png(save_title_i )

}

However, I don't think I am doing this right since the outputs are being corrupted:

enter image description here

Can someone please show me how to fix this?

Thanks!

CodePudding user response:

If you want to save the plot locally you need to remember two things:

  1. use png()(bmp, jpeg, pdf etc.) before the plot to open the file
  2. use dev.off() after the plot to close the file

*In addition, you can change the dimensions of the plot you want to save by: png(save_title_i , width = 800, height = 800)

for (i in 1:length(factors))
{
  index_i = factors[[i]]
  title_i = paste0("Tree Map", index_i)
  data_i = my_data[which(my_data$var1 == index_i),]
  
  save_title_i = paste0("treemap_",i, ".png")
  png(save_title_i ) # open the file
  
  treemap_i = treemap(data_i, index = c("var1", "var2"), vSize = "counts", type = "index", palette = "Set1", title = title_i)
  
  my_list[[i]] = treemap_i

  dev.off() # close the file
}
  • Related