How to save a plot in R in a subdirectory of the working directory

本秂侑毒 提交于 2019-12-06 04:12:06

问题


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?

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

回答1:


Try this:

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.

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

Notes

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) Also note the savePlot command which is given after (rather than before) the plotting command.




回答2:


This will work:

png(filename="new/name.png")    #will work if "new" folder is already in your working directory
data(mtcars)
plot(mtcars$wt, mtcars$mpg, main="Scatterplot Example",  xlab="Car Weight ", ylab="Miles Per Gallon ", pch=19)
dev.off()

If you do not already have the "new" folder in your working directory, you can create the same using dir.create() as mentioned in G. Grothendieck's answer.

Also, dev.off() is necessary as it shuts down the specified (by default the current) device. Without it, you cannot view the created image.



来源:https://stackoverflow.com/questions/27817546/how-to-save-a-plot-in-r-in-a-subdirectory-of-the-working-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!