Assume the following data:
library(ggplot2)
set.seed(1)
X <- data.frame(
x = 1:10,
y = sample(1:20, 10),
group = sample(paste0("g", 1:3), 10, replace = TRUE),
type = rep(c("a", "b"), each = 5),
style = rep(c(0, 1), each = 5)
)
> X
x y group type style
1 1 6 g1 a 0
2 2 8 g1 a 0
3 3 11 g3 a 0
4 4 16 g2 a 0
5 5 4 g3 a 0
6 6 14 g2 b 1
7 7 15 g3 b 1
8 8 9 g3 b 1
9 9 19 g2 b 1
10 10 1 g3 b 1
And the plot below:
ggplot(X, aes(x, y)) +
geom_point(aes(color = group)) +
facet_grid(. ~ type)
Which looks like this:
The goal is to add a geom_hline
with yintercept = 10
, but only to the left grid (everything else should remain the same). I tried the script below:
ggplot(X, aes(x, y)) +
geom_point(aes(color = group)) +
geom_hline(aes(linetype = style), yintercept = 10) + # does not work
# geom_hline(data = X[X$type == "b", ], yintercept = 10) + # doesn't work neither
facet_grid(. ~ type)
But it adds an horizontal line to both grids. Any workaround?
Solution:
geom_hline(data = data.frame(yint = 10, type = "b"), aes(yintercept = yint)) +