Search code examples
rmacosimagefilepng

Image Files are not Stored with Specified Dimensions in R


So I am trying to save images as files. For instance, like this:

 
  png("image.png", units = "in", res = 500, width = 35, 
      height = 35, pointsize = 40)
  
  plot(density(rnorm(1000)))
  
  dev.off()

I am expecting a PNG image file of dimension 35 X 35 inches with resolution 500 pixels/inch. However, when inspecting the image file with finder on MAC, the image file turns out to be of size 243.06 X 243.06 inches and 72 pixels per inch.

This is the information I get when opening the image with Preview and choosing tools and adjust size.

enter image description here

Any ideas what could be causing this issue?


Solution

  • The relatively new-ish ragg package provides nicely modern graphic devices that are more efficient and higher quality than the default graphics devices--and apparently it does a better job encoding the resolution into the the file so your viewers will default to the resolution you want.

    Comparing these two files:

    png("sample_png.png", units = "in", res = 500, width = 35, 
          height = 35, pointsize = 40)
      
    plot(density(rnorm(1000)))
      
    dev.off()
    
     
    library(ragg) 
    agg_png(
      filename = "sample_agg.png",
      units = "in", res = 500, width = 35, 
      height = 35, pointsize = 40
    )
    
    plot(density(rnorm(1000)))
      
    dev.off()
    

    The ragg PNG defaults to 500 dpi when opened in Preview, and the ragg file is also 1.6 MB compared to 6.2 MB with png().