【问题标题】:geom_raster comes out "smeared" when saving to PDF保存为 PDF 时 geom_raster 出现“涂抹”
【发布时间】:2026-02-07 12:55:02
【问题描述】:

当我保存一个使用 geom_raster 的 ggplot 时,瓷砖会出现“涂抹”。如果我使用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()

【问题讨论】:

  • 也许贴一两个屏幕截图,以便我们可以轻松了解您的意思?
  • 谢谢。将geom_raster 转换为geom_tile 对我有用。

标签: r pdf ggplot2


【解决方案1】:

这可能是由于您的 PDF 查看器执行了interpolation of the raster。我在我的 Mac 上重新创建了您的“smeared2.pdf”(见下文),它在 Adob​​e Reader(右)中看起来很好,在预览中(左)看起来很模糊。根据您的 PDF 查看器,您可以通过更改设置来消除模糊效果。例如,在预览中,在首选项下的 PDF 选项卡中,您可以取消选中“平滑文本和艺术线条”,PDF 将正确显示。

【讨论】:

  • 我没有考虑过使用不同的阅读器。是的,我正在使用预览。我能做些什么来防止这种情况发生吗?
  • 是的。按照我的回答中的说明更改预览的设置。
  • 谢谢。使用 geom_tile 是“更便携”,还是人们“应该”关闭的设置?
  • 我不确定。这是我第一次遇到这个问题。但是我通常在这种情况下使用 geom_tile 并且之前没有使用过 geom_raster。
最近更新 更多