Search code examples
rggplot2cowplot

The draw_image() function from cowplot results in blurred pdfs


Reading a vectorized pdf sometimes result in a badly blurred image with the draw_image() function from cowplot:

library(ggplot2)
library(cowplot)
library(magick)

# make pdf input as example
p <- ggplot(iris, aes(Sepal.Length, Sepal.Width, shape = Species)) + 
  geom_point() + scale_shape_manual(values = 21:23) + theme_classic()
ggsave("input.pdf", p, width = 6, height = 4.2)

# now draw with draw_image() and then write as png
fig <- ggdraw() + draw_image("input.pdf")
ggsave("output.png", fig, width = 1, height = .7, dpi = 1200) # blurred image

enter image description here

However, reading SVGs works fine:

fig <- ggdraw() +
  draw_image("http://jeroen.github.io/images/tiger.svg")
ggsave("output.png", fig, width = 1, height = .7, dpi = 1200)

enter image description here

Also, using:

magick::image_read_pdf("input.pdf")

results in a non-blurry output.


Solution

  • I'm not entirely sure why SVGs and pdfs are handled differently, or what exactly happens when you read pdfs with magick::image_read() (which is what draw_image() uses internally), but one solution is to use magick::image_read_pdf() inside of draw_image(). The function magick::image_read_pdf() converts the pdf into a raster image, and we can specify the resolution we want with the density argument:

    fig <- ggdraw() + draw_image(magick::image_read_pdf("input.pdf", density = 600))
    ggsave("output.png", fig, width = 1, height = .7, dpi = 1200)
    

    enter image description here