首页 > 解决方案 > 使用 png() 搜索将图片保存在预定义位置的方法,类似于使用 ggsave() 的成功方法

问题描述

我正在使用两种不同的图形:1.) 使用 ggplot2 创建的箱线图和 2.) 相关表。

我想将这两个图形保存在用户可以通过提示选择的位置下,使用:

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)
}

现在,我正在使用此代码来选择要保存图形的位置:

folder = choose_dir()

为了保存我的图形,我对使用 ggsave 的箱线图没有任何问题:

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

但是,我无法以与 ggsave 相同的方式保存相关表图片,即使我尝试了许多不同的方法:

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

没有任何效果。非常感谢任何帮助的人!

标签: rpng

解决方案


您需要为png.

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

您也可以更改/\\.

编辑:为了更正确和安全,这是@r2evans 提供的正确代码。

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

推荐阅读