Search code examples
rpdfggplot2png

ggplot writes to pdf and png with very different sizes


I create a grid with 4 plots and then write it to a pdf as well as to a png. For reasons I don't understand, the charts and fonts plot differently (much smaller in the png than in the pdf). The commands I use are:

pdf("Cusum Page 1.pdf")
  grid.arrange(log_return_plot, tracking_error_plot, 
               ir_graph, excess_vol, 
               layout_matrix = rbind(c(1, 2), c(3, 4)))
dev.off()

and

png(filename = "Cusum Page 1.png", width = 800, height = 800, units = "px",
    pointsize = 12, bg = "white", res = NA, family = "", restoreConsole = TRUE,
    type = c("windows", "cairo", "cairo-png"), antialias = "d")   

  grid.arrange(log_return_plot, tracking_error_plot, 
               ir_graph, excess_vol, 
               layout_matrix = rbind(c(1, 2), c(3, 4)))

dev.off()

I have tried changing and cutting out various options in the png call, with no success - I just can't make my png and pdf look identical. Is the root cause of this problem known? I'd greatly appreciate suggestions on settings that I should try changing in order to make the two exports identical.

Sincerely and with many thanks in advance

Thomas Philips


Solution

  • I suspect this is something to do with setting the width and height arguments of each option and making the png::res (nominal resolution) and pdf::pointsize (defaults to 12) agree.

    pdf dimensions default to inches so I've made the png follow suit.

    Here's an initial attempt at a resolution.

    library(gridExtra)
    library(ggplot2)
    
    
    pdf("Cusum Page 1.pdf", width = 6, height = 6)
    grid.arrange(p1, p2, p3, p4, 
                 layout_matrix = rbind(c(1, 2), c(3, 4)))
    dev.off()
    
    
    
    png(filename = "Cusum Page 2.png", width = 6, height = 6, units = "in",
        pointsize = 12, bg = "white", res = 144, family = "", restoreConsole = TRUE,
        type = c("windows", "cairo", "cairo-png"), antialias = "d")   
    
    grid.arrange(p1, p2, p3, p4, 
                 layout_matrix = rbind(c(1, 2), c(3, 4)))
    
    dev.off()
    
    

    graphs

    
    p1 <- 
      ggplot(iris) + 
      geom_histogram(aes(Sepal.Length))
    
    p2 <-  
      ggplot(iris) + 
      geom_histogram(aes(Sepal.Width))
    
    p3 <- 
      ggplot(iris) + 
      geom_histogram(aes(Petal.Length))
    
    p4 <-  
      ggplot(iris) + 
      geom_histogram(aes(Petal.Width))
    
    

    Created on 2021-07-12 by the reprex package (v2.0.0)

    png png

    pdf - converted to jpg to enable uploading

    pdf - converted to jpg to enable uploading