如何在工作目录的子目录中的R中保存图 [英] How to save a plot in R in a subdirectory of the working directory

查看:62
本文介绍了如何在工作目录的子目录中的R中保存图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将R中的图保存到当前工作目录的子目录中?我尝试了以下操作,但这不起作用。我不确定如何将工作目录连接到所需的文件名。

Is it possible to save a plot in R into a subdirectory of the current working directory? I tried the following, but that doesn't work. I'm not sure how to concatenate the working directory to the file name I want.

  wd <- getwd()

  png(filename=wd+"/img/name.png")

  counts <- table(dnom$Variant, dnom$Time)
  barplot(counts, main="Distribution of Variant and words of time",
    xlab="Temporal nouns", col=c("paleturquoise3", "palegreen3"),
    legend = rownames(counts))

此外,图像导出功能的默认保存目录是什么?

Also, what's the default save directory for the image export functions?

在下面执行David的建议时,返回的错误是:

When running David's suggestion below the error returned is:

Error in png(filename = paste0(wd, "/img/name.png")) : 
  unable to start png() device
In addition: Warning messages:
1: In png(filename = paste0(wd, "/img/name.png")) :
  unable to open file 'D:/Dropbox/Corpuslinguïstiek project/antconc resultaten/img/name.png' for writing
2: In png(filename = paste0(wd, "/img/name.png")) : opening device failed


推荐答案

尝试一下:

File <- "./img/name.png"
if (file.exists(File)) stop(File, " already exists")
dir.create(dirname(File), showWarnings = FALSE)

png(File)

# ... whatever ...

dev.off()

如果

Omit the if statement if its ok to overwrite the file.

如果 img 存在,则 dir。 create 可以选择省略。 (如果您尝试创建一个已经存在的目录,则不会造成问题。)

If img exists then dir.create could be optionally omitted. (If you try to create a directory that is already there it won't cause a problem.)

注释

1)另一个可能性是将 img 放在主目录中。我们可以使用 png(〜/ img / name.png)将文件保存到 img 目录中主目录。如果不确定主目录是哪个目录,请尝试 path.expand(〜)

1) Another possility is to put img in the home directory. We could use png("~/img/name.png") to save the file to the img directory in the home directory. If unsure which directory is the home directory try path.expand("~").

2)另请注意 savePlot 命令,该命令是在绘图命令之后(而不是之前)给出的。

2) Also note the savePlot command which is given after (rather than before) the plotting command.

这篇关于如何在工作目录的子目录中的R中保存图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆