rggplot2geom-histogram

How to remove outline between columns in geom_histogram


I have a histogram that uses color to distinguish categories of data. When I make the plot, there is a line across the whole thing using the last color in the sequence. It looks bad since there are a lot of gaps in the data.

Here's a MRE using cars:

library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(x=mpg)) + geom_histogram(bins=15, colour='red')

Note that there are two columns with 0 values in them, but they still have the red outline. I would like to remove that if possible.

I was able to hide it with a horizontal line, but I was hoping there was a better way to do it without adding another geom.

library(ggplot2)
data(mtcars)

ggplot(mtcars, aes(x=mpg)) + 
geom_histogram(bins=15, colour='red') +   
geom_hline(yintercept = 0, color = "white")

Solution

  • You can change the computation on the y-axis to return NA values if the frequency is 0 instead. It will return a Removed 8 rows containing missing values ('position_stack()'). warning, but the plot returned is correct:

    ggplot(mtcars, aes(x = mpg,
                       y = ifelse(after_stat(count) > 0, after_stat(count), NA))) +
      geom_histogram(binwidth = 1, colour='red') 
    

    enter image description here