更改颜色并填写 geom_histogram 会导致在 y=0 中自动打印行

Changing color and fill in geom_histogram results in automatically printed line in y=0

我有

写成

ggplot(aa, aes(x = laengde)) + theme_bw() + 
  geom_histogram(bins=30)

按如下方式更改颜色会导致 y=0 处出现不需要的行。我怎样才能删除这条线?

写成

ggplot(aa, aes(x = laengde)) + theme_bw() + 
  geom_histogram(bins=30,
                 color = "#6DBCC3",
                 fill = alpha("#6DBCC3", .2))

和数据

aa <- structure(list(laengde = c(56L, 52L, 52L, 52L, 52L, 53L, 54L, 
54L, 54L, 55L, 54L, 51L, 52L, 57L, 53L, 50L, 52L, 54L, 50L, 56L, 
52L, 51L, 47L, 52L, 52L, 54L, 55L, 53L, 54L, 53L, 51L, 49L, 50L, 
57L, 52L, 54L, 59L, 53L, 54L, 54L, 58L, 53L, 52L, 53L, 54L, 55L, 
52L, 52L, 52L, 55L)), row.names = c(NA, -50L), class = "data.frame")

这些线实际上是直方图中计数为 0 的 bin。要屏蔽它们,您可以将这些容器的颜色设置为透明。在下面的示例中,我们使用 after_scale 函数访问由层的统计部分计算的 count 列并直接设置颜色(而不是将颜色映射到比例)。

library(ggplot2)

aa <- structure(list(laengde = c(56L, 52L, 52L, 52L, 52L, 53L, 54L, 
                                 54L, 54L, 55L, 54L, 51L, 52L, 57L, 53L, 50L, 52L, 54L, 50L, 56L, 
                                 52L, 51L, 47L, 52L, 52L, 54L, 55L, 53L, 54L, 53L, 51L, 49L, 50L, 
                                 57L, 52L, 54L, 59L, 53L, 54L, 54L, 58L, 53L, 52L, 53L, 54L, 55L, 
                                 52L, 52L, 52L, 55L)), row.names = c(NA, -50L), class = "data.frame")

ggplot(aa, aes(x = laengde)) + theme_bw() + 
  geom_histogram(
    bins=30,
    aes(colour = after_scale(ifelse(count == 0, "transparent", "#6DBCC3"))),
    fill = alpha("#6DBCC3", .2))

reprex package (v1.0.0)

于 2021-03-08 创建