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.
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)
# 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With