Search code examples
rpng

Search for way to save picture in predefined location with png(), similar to successful approach using ggsave()


I am using two different kinds of graphics: 1.) a boxplot created with ggplot2 and 2.) a correlation table.

I want to save both graphics under a location that can be chosen by the user through a prompt, using:

library(easycsv)
choose_dir = function(){
    os = Identify.OS()
    if(tolower(os) == "windows"){
        directory <- utils::choose.dir()
    }
    if(tolower(os) == "macosx"){
        system("osascript -e 'tell app \"RStudio\" to POSIX path of (choose folder with prompt \"Choose Folder:\")' > /tmp/R_folder",
        intern = FALSE, ignore.stderr = TRUE)
        directory <- system("cat /tmp/R_folder && rm -f /tmp/R_folder", intern = TRUE)
    }
    return(directory)
}

Now, I am using this code to choose the location I want to save the graphics in:

folder = choose_dir()

To save my graphics, I have no issue with the boxplot using ggsave:

ggsave("SL_Boxplot.png", path = folder, width=7, height= 0.7, dpi=500, units = "cm", scale = 5.2)

However, I am unable to save the correlation table picture in the same way as with ggsave, even though I tried many different ways:

png("folder/Correlation_Table.png", width = 30, height = 25, pointsize = 8, res = 700, units = "cm")

nothing works. Very grateful for anyone helping out!


Solution

  • You need to make a valid path for png.

    png(paste0(folder,"/Correlation_Table.png"), width = 30, height = 25, pointsize = 8, res = 700, units = "cm")
    

    You can also change / to \\.

    Edits: to be more proper and safe, this is the correct code provided by @r2evans.

    png(file.path(folder, "Correlation_Table.png"), width = 30, height = 25, pointsize = 8, res = 700, units = "cm")