Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use dev.print to copy current graphics device to PNG of particular size in R

Tags:

r

A very basic dev.print() question in R. I have been trying to print the following to PNG:

hist(rnorm(1000),  xlab  = "x", ylab = "density", probability=T)
abline(h=0)
dev.print(device = png, filename = "file.png", width = 8, height = 8)

But I get:

Error in grDevices::dev.copy(device = function (filename = "Rplot%03d.png", : invalid graphics state

I am specifically trying to understand how to capture the displayed screen plot in base R to a PNG of a specific size and a filename.

I also tried

savePlot(filename = "tes.png", device = png, height = 8, width = 8)

but I got the expected error

Error in savePlot(filename = "tes.png", device = png, height = 8, width = 8) : unused arguments (height = 8, width = 8)

since savePlot does not allow for variable arguments.

like image 669
user3236841 Avatar asked Sep 02 '25 04:09

user3236841


1 Answers

It seems specifying the units-argument of dev.print() helps.

# before
> list.files()
character(0)
hist(rnorm(1e3),  xlab='x', ylab='density', probability=TRUE) 
abline(h=.2)
dev.print(device=png, filename='file.png', units='cm', width=8, height=8, res=72)

file.png

# after
> list.files()
[1] "file.png"

> sessionInfo()
R version 4.5.0 (2025-04-11)
Platform: aarch64-apple-darwin20
Running under: macOS Sequoia 15.2

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib 
LAPACK: /Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.1

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: Europe/Berlin
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods  
[7] base         
like image 181
Friede Avatar answered Sep 05 '25 00:09

Friede