Home > Net >  R png function not working when adding "{filename}.png" extension
R png function not working when adding "{filename}.png" extension

Time:12-30

I am trying to save a plot in png format. I am using the following code:

p <- ggplot(mtcars) 
  geom_point(aes(x = hp, y = mpg))

png(filename = 'filename.png')
p
dev.off()

However, when I run without the file extension, it works:

p <- ggplot(mtcars) 
  geom_point(aes(x = hp, y = mpg))

png(filename = 'filename')
p
dev.off()

The following error is raised:

Error in png(filename = "filename.png") : 
  não é possível iniciar dispositivo png()
In addition: Warning messages:
1: In png(filename = "filename.png") :
  unable to open file 'filename.png' for writing
2: In png(filename = "filename.png") : opening device failed

The error is independent if I use png(), jpeg() or ggsave() functions.

UPDATE:

  • I already tried to clear my workspace, restarted the computer, and tried different folders with different access scopes. It only works if I don't use the *.png, *.jpeg or *.pdf extensions.
  • It works for *.svg extensions.
  • If I try to rename the file to add the .png extension, it does not work due to "access denied". But if I rename to add .svg extension, it works and converts the file to .svg.

Thanks all in advance :)

CodePudding user response:

Update: I got it: There must be some masking or kind of overlapping between different packages with png() function. When using grDevices package it works in contrast to png() function from png package:

library(grDevices)
library(ggplot2)

ggplot(mtcars) 
  geom_point(aes(x = hp, y = mpg))

grDevices::png(filename = 'filename7.png')
p
dev.off()

First answer: Replace filename by file: Then it should work:

This is a good question. I can't figure out why this happens, because the argument is filename.

library(png)
library(ggplot2)

p <- ggplot(mtcars) 
  geom_point(aes(x = hp, y = mpg))

png(file = 'filename.png')
#or
png('filename.png')

p
dev.off()

CodePudding user response:

From what I have read, it seems that png() functions with 'file =' and not 'filename ='. Additionally, you it seems like you need to specify the entire directory like this: png(file = 'C:/users/name/file/etc.png This initial answer may be incomplete so here is a link to a more complete (and well-supported) answer.

  •  Tags:  
  • r
  • Related