在geom_hline

时间:2019-08-08 14:14:43

标签: r ggplot2

我正在创建一个均值为水平线的条形图,并希望对高于平均值的条形进行着色,但只能绘制该条形的顶部。这可能吗?

test <- iris %>% group_by(Species) %>% summarise(avg = mean(Sepal.Length))

ggplot(test, aes(x = Species, y = avg)) +
  geom_bar(stat = "identity") +
  geom_hline(yintercept = mean(test$avg))

enter image description here

所需的输出:

enter image description here

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

这可能不是最佳解决方案,但它可以起作用:

test <- iris %>% group_by(Species) %>% summarise(avg = mean(Sepal.Length))
test2 <- iris %>% group_by(Species) %>% 
  summarise(avg = mean(Sepal.Length)) %>% 
  mutate(avg, avg = ifelse(avg > mean(avg), mean(avg), avg))

ggplot(test, aes(x = Species, y = avg)) +
  geom_bar(stat = "identity", data=test, fill="red") +
  geom_bar(stat = "identity", data=test2) +
  geom_hline(yintercept = mean(test$avg))

enter image description here