Adding horizontal lines to a ggplot-barchart with

2019-08-25 09:58发布

问题:

In this plot

df <- data.frame(factor = as.factor(c(rep("A",3), rep("B",3))), Treatment = c(rep(c("A","B","C"),2)), values=runif(6,0,1))

ggplot(df, aes(Treatment, values))+
  geom_bar(stat="identity", position="dodge") +
  facet_wrap(~factor)

how can i add a geom_hline to each facet with the yintercept of a given Treatment-level (e.g. "A")

+geom_hline(data=df, aes(yintercept= df[df$Treatment=="A",]))

does not work:

Error: Aesthetics must be either length 1 or the same as the data (6): yintercept

回答1:

library(tidyverse)

df <- data.frame(factor = as.factor(c(rep("A",3), rep("B",3))), Treatment = c(rep(c("A","B","C"),2)), values=runif(6,0,1))

ggplot(df, aes(Treatment, values))+
  geom_bar(stat="identity", position="dodge") +
  facet_wrap(~factor) +
  geom_hline(data = df %>% filter(Treatment == "A"), aes(yintercept = values))

Created on 2018-03-23 by the reprex package (v0.2.0).



标签: r ggplot2