1

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

Danilo Steckelberg
  • 320
  • 1
  • 2
  • 11

1 Answers1

2

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()
TarJae
  • 72,363
  • 6
  • 19
  • 66