删除geom_bar中边框的底部边框

时间:2019-11-12 11:45:26

标签: r ggplot2 geom-bar

我正在寻找一种在geom_bar中添加时删除不重叠底部边框的方法。我不想使用像geom_hline(yintercept = 0, colour = "white")这样的选项,听起来很挑剔,因为它覆盖了原始条的单行像素。我猜想我可能必须直接修改ggproto对象的内部,但是我不知道该怎么做。

示例代码:

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

enter image description here

所需的输出:

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用

禁用黑色边框
geom_bar(..., colour = "NA")

然后需要重新绘制它们。 根据需要调整width+/- 0.5,以适当地间隔条形图。

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)