Reputation: 28437
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
Upvotes: 7
Views: 23454
Reputation: 269644
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.
Upvotes: 5
Reputation: 3158
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.
Upvotes: 1