cowplot 中的 draw_image() 函数导致 pdf 模糊
The draw_image() function from cowplot results in blurred pdfs
使用 cowplot 的 draw_image()
函数读取矢量化 pdf 有时会导致图像严重模糊:
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
但是,读取 SVG 效果很好:
fig <- ggdraw() +
draw_image("http://jeroen.github.io/images/tiger.svg")
ggsave("output.png", fig, width = 1, height = .7, dpi = 1200)
另外,使用:
magick::image_read_pdf("input.pdf")
产生不模糊的输出。
我不完全确定为什么 SVG 和 pdf 的处理方式不同,或者当您使用 magick::image_read()
(这是 draw_image()
内部使用的)阅读 pdf 时到底发生了什么,但一个解决方案是在 draw_image()
中使用 magick::image_read_pdf()
。函数 magick::image_read_pdf()
将 pdf 转换为光栅图像,我们可以使用 density
参数指定我们想要的分辨率:
fig <- ggdraw() + draw_image(magick::image_read_pdf("input.pdf", density = 600))
ggsave("output.png", fig, width = 1, height = .7, dpi = 1200)
使用 cowplot 的 draw_image()
函数读取矢量化 pdf 有时会导致图像严重模糊:
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
但是,读取 SVG 效果很好:
fig <- ggdraw() +
draw_image("http://jeroen.github.io/images/tiger.svg")
ggsave("output.png", fig, width = 1, height = .7, dpi = 1200)
另外,使用:
magick::image_read_pdf("input.pdf")
产生不模糊的输出。
我不完全确定为什么 SVG 和 pdf 的处理方式不同,或者当您使用 magick::image_read()
(这是 draw_image()
内部使用的)阅读 pdf 时到底发生了什么,但一个解决方案是在 draw_image()
中使用 magick::image_read_pdf()
。函数 magick::image_read_pdf()
将 pdf 转换为光栅图像,我们可以使用 density
参数指定我们想要的分辨率:
fig <- ggdraw() + draw_image(magick::image_read_pdf("input.pdf", density = 600))
ggsave("output.png", fig, width = 1, height = .7, dpi = 1200)