假设以下数据:
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
以下情节:
ggplot(X, aes(x, y)) +
geom_point(aes(color = group)) +
facet_grid(. ~ type)
看起来像这样:
目标是使用geom_hline
添加yintercept = 10
,但仅添加到左侧网格(其他所有内容应保持不变)。我尝试了下面的脚本:
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)
但它为两个网格添加了一条水平线。任何解决方法?
解决方案:
geom_hline(data = data.frame(yint = 10, type = "b"), aes(yintercept = yint)) +