geom_raster 保存为 PDF 时出现 "smeared"

geom_raster comes out "smeared" when saving to PDF

当我保存一个使用 geom_raster 的 ggplot 时,会出现图块 "smeared"。如果我使用 ggsave()pdf(),结果相同。 geom_tileimage 没有这个问题。我在 RStudio、X11 或 PNG 图形设备上没有这个问题。

这是什么原因造成的?我该如何解决?

示例:

library(ggplot2)

## doesn't work: tiles are smeared together

ggsave("smeared1.pdf",
  ggplot(cbind(expand.grid(x = 1:3, y = 1:3), fill = rnorm(9))) +
    geom_raster(aes(x = x, y = y, fill = fill)))

pdf("smeared2.pdf")
ggplot(cbind(expand.grid(x = 1:3, y = 1:3), fill = rnorm(9))) +
    geom_raster(aes(x = x, y = y, fill = fill))
dev.off()

## works fine

ggsave("not-smeared0.png",
  ggplot(cbind(expand.grid(x = 1:3, y = 1:3), fill = rnorm(9))) +
    geom_raster(aes(x = x, y = y, fill = fill)))

ggsave("not-smeared1.pdf",
  ggplot(cbind(expand.grid(x = 1:3, y = 1:3), fill = rnorm(9))) +
    geom_tile(aes(x = x, y = y, fill = fill)))

pdf("not-smeared2.pdf")
ggplot(cbind(expand.grid(x = 1:3, y = 1:3), fill = rnorm(9))) +
  geom_tile(aes(x = x, y = y, fill = fill)))
dev.off()

pdf("not-smeared3.pdf")
image(matrix(rnorm(9), 3))
dev.off()

这可能是因为您的 PDF 查看器正在执行 interpolation of the raster。我在我的 Mac 上重新创建了您的 "smeared2.pdf"(见下文),它在 Adob​​e Reader(右)中看起来不错,但在预览(左)中看起来很模糊。根据您的 PDF 查看器,您可以通过更改设置来消除模糊效果。例如,在预览中,在首选项下的 PDF 选项卡中,您可以取消选中 "Smooth Text and Line Art",PDF 将正常显示。