cmirian
cmirian

Reputation: 2253

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

I have

enter image description here

Written with

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

Changing color as follows results in an unwanted line at y=0. How can I remove this line?

enter image description here

Written with

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

And data

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

Upvotes: 0

Views: 233

Answers (1)

teunbrand
teunbrand

Reputation: 38003

Those lines are actually bins in the histogram that have 0 counts. To mask them, you can set the colour of those bins to transparent. In the example below, we use the after_scale function to access the count column computed by the stat part of the layer and to set colour directly (as opposed to mapping colours to a scale).

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

Created on 2021-03-08 by the reprex package (v1.0.0)

Upvotes: 3

Related Questions