如何在geom_line中添加带有单独图例的参考线?

时间:2020-09-25 12:51:09

标签: r ggplot2

我有一个小的数据集,需要用参考线绘制。

ex <- tibble(name = rep(c("A","B","C"),each = 3),
             group = rep(c("group1","group2","group3"), 3),
             value = c(1,2,3,1.5,2.5,3,0.5,1.8,4))
ex %>% 
  ggplot(aes(x = group, y = value, color = name, group = name)) +
  geom_line()`

这给了我:
plot 1

现在,我想添加参考线。我可以这样添加点:

ex %>% 
  ggplot(aes(x = group, y = value, color = name, group = name)) +
  geom_line() +
  geom_point(aes(x = "group1", y = 3, fill = "ref")) +
  geom_point(aes(x = "group2", y = 3, fill = "ref")) +
  geom_point(aes(x = "group3", y = 3, fill = "ref"))

哪个给我:
plot 2

现在我该如何连接点并仍然将此线作为单独的图例?如果我将更多行添加到带有参考值的原始小标题中,则可以添加该行,但该行会显示在原始图例中,并且需要在单独的一行(例如点)中添加它。


ex <- ex %>% 
  add_row(name = "ref",
          group = "group1",
          value= 3) %>% 
  add_row(name = "ref",
          group = "group2",
          value= 3) %>% 
  add_row(name = "ref",
          group = "group3",
          value= 3)

ex %>% 
  ggplot(aes(x = group, y = value, color = name, group = name)) +
  geom_line() +
  geom_point(aes(x = "group1", y = 3, fill = "ref")) +
  geom_point(aes(x = "group2", y = 3, fill = "ref")) +
  geom_point(aes(x = "group3", y = 3, fill = "ref"))

哪个给我这个:
plot 3

我想念什么?

0 个答案:

没有答案