【问题标题】:Changing color and fill in geom_histogram results in automatically printed line in y=0更改颜色并填充 geom_histogram 会在 y=0 中自动打印线
【发布时间】:2021-06-06 11:52:16
【问题描述】:

我有

写成

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")

【问题讨论】:

标签: r ggplot2 plot histogram


【解决方案1】:

这些线实际上是直方图中的 bin,计数为 0。要屏蔽它们,您可以将这些箱的颜色设置为透明。在下面的示例中,我们使用 after_scale 函数访问由图层的 stat 部分计算的 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 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2017-06-11
    • 2021-12-24
    • 1970-01-01
    • 2018-05-04
    • 2019-12-04
    相关资源
    最近更新 更多