向ggplot2添加水平线

3
我正在使用R中的ggplot2库。
假设我有一个看起来像这样的图表:
library(ggplot2)

ggplot(work) + geom_line(aes(x = var1, y = var2, group = 1)) +
               theme(axis.text.x = element_text(angle = 90)) +
               ggtitle("sample graph")

有没有一种方法可以直接向这个图表添加第二条线?

例如:

ggplot(work) + geom_line(aes(x = var1, y = var2, group = 1)) +
               geom_line(aes(x = var1, y = mean(var2), group = 1)) +
               theme(axis.text.x = element_text(angle = 90)) +
               ggtitle("Sample graph")

谢谢


5
如果您能提供一个小的可复制示例以及期望输出,那么帮助您就会更容易。请阅读如何提供可复制示例 - Ronak Shah
1
你的代码中有几个拼写错误:忘记了) - 看起来在上面的编辑后它似乎可以工作。如@Ronak Shah所建议的,如果它仍然不能按照你的期望工作,请提供最小可重现示例(MRE)。 - Waldi
geom_hline(yintercept = mean(var2))的翻译是什么? - Rui Barradas
1个回答

7

确实是可能的:

library(ggplot2)
ggplot(mtcars, aes(x = mpg)) +
        geom_line(aes(y = hp), col = "red") +
        geom_line(aes(y = mean(hp)), col = "blue")

enter image description here

然而,对于特定的水平线,我会使用 geom_hline

ggplot(mtcars, aes(x = mpg, y = hp)) +
        geom_line(col = "blue") +
        geom_hline(yintercept = mean(mtcars$hp), col = "red")

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接