Search code examples
rggplot2geom-bar

Removing the bottom border for borders in geom_bar


I'm looking for a way to remove the non-overlapping bottom border when added in geom_bar. I don't want to use an option like geom_hline(yintercept = 0, colour = "white"), as nitpicky as it sounds as it covers the original bar's single line of pixels. I'm guessing I might have to modify the internals of the ggproto object directly but I don't know how to go about doing that.

Sample code:

plot <- iris %>% ggplot(aes(Species, Sepal.Length, fill = Species)) +
  geom_bar(stat = "summary", fun.y = "mean", colour = "black")

enter image description here

Desired output:

enter image description here


Solution

  • You can disable the black borders with

    geom_bar(..., colour = "NA")
    

    and then re-draw them were needed. Adjust width and +/- 0.5 as needed to space the bars appropriately.

    library(dplyr)
    library(ggplot2)
    
    
    x <- iris %>%
      group_by(Species) %>%
      summarise(m=mean(Sepal.Length)) %>%
      mutate(Species.x = as.integer(as.factor(Species))) %>% ungroup
    y <- bind_rows(
      x %>%
        mutate(
          Species.x = Species.x - 0.5,
          y = 0
        ),
      x %>%
        mutate(
          Species.x = Species.x - 0.5,
          y = m
        ),
      x %>%
        mutate(
          Species.x = Species.x + 0.5,
          y = m
        ),
      x %>%
        mutate(
          Species.x = Species.x + 0.5,
          y = 0
        )
    )
    
    ggplot(x, aes(Species.x, m)) +
        geom_col(aes( fill=Species), colour=NA, width=1) +
      geom_path(data=y, aes(y=y, group=Species), color='black') +
      scale_x_continuous(breaks=x$Species.x, labels=x$Species)