4

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

Nautica
  • 2,004
  • 1
  • 12
  • 35
  • Maybe this is relevant? https://stackoverflow.com/q/13701347/680068 – zx8754 Nov 12 '19 at 12:00
  • @zx8754 Unfortunately no; in my real code I have the axes expansions nulled like the selected answer, but my fundamental issue remains of the bottom border appearing. – Nautica Nov 12 '19 at 12:10
  • We don't want to see that line because of aesthetics, or does it have other technical reasons: for example, in final plots we want to add another plot from the bottom? – zx8754 Nov 12 '19 at 12:13
  • 1
    Just aesthetics. If it was a one off plot I would have just modified it in an image editor as needed but the code is inside a Shiny app which has reactive user input. – Nautica Nov 12 '19 at 12:17

1 Answers1

3

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)
MrGumble
  • 5,631
  • 1
  • 18
  • 33