首页 > 解决方案 > 如何防止 geom_rect 在矩形之间添加水平像素线?

问题描述

我的渲染代码使用 geom_rect 来显示相邻的彩色矩形行,但是,尽管将边框颜色设置为 NA 并将边框大小设置为零,但矩形之间仍然存在单个像素高的水平线。

我正在使用 ggplot2 v3.3.3 在 macOS v11.2.3 上使用 R v4.0.3。

这是一些重现问题的代码:

library(ggplot2)

regions <- data.frame(name = c("A", "B", "C", "D"),
                      left = c(0, 4, 0, 3), right = c(4, 5, 3, 5),
                      top = c(6, 6, 2, 2), bottom = c(2, 2, 0, 0),
                      colour = c("lightgrey", "gold", "lightgrey", "blue"))

plot <- ggplot() + 
  theme_minimal() +
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(), 
        legend.position = "none") +
  geom_rect(data = regions, 
            mapping = aes(xmin = left, xmax = right, 
                          ymin = bottom, ymax = top, 
                          fill = colour), 
            colour = NA, size = 0) +
  scale_fill_identity() +
  geom_text(data = regions, 
            mapping = aes(x = left + (right - left) / 2, 
                          y = bottom + (top - bottom) / 2, 
                          label = name)) +
  xlab("") + ylab("")

ggsave("~/Desktop/borders.png", plot = plot, 
       units = "cm", width = 10, height = 10, dpi = 600)

图像如下所示:

这个

当我放大以显示问题时,水平线如下所示:

这个

我知道它很微弱,但是当我将许多行矩形一起渲染时,问题会导致微妙的水平条纹,这会分散观众对我正在呈现的数据的注意力。

我已经尝试打印图像并在 Windows 7(在 MS Paint 中)上查看它,线条仍然可见。

这可能是有人解释说我不了解图像格式或抗锯齿或其他东西的时候。很好 :-) 如果问题“是”抗锯齿,我可以为 geom_rect 图层删除它,但为其他所有内容保留它吗?

在此先感谢,你们可爱的人。

编辑:antialias = "none"ggsave()调用中使用会从矩形中删除线条,但也会使文本看起来很糟糕,因为它也不再抗锯齿。抗锯齿可以在单个几何级别控制吗?

标签: rggplot2

解决方案


推荐阅读