R:向ggplot2添加水平线

我在 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")

谢谢

回答

确实有可能:

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

但是,对于特定的水平线,我会使用geom_hline

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


以上是R:向ggplot2添加水平线的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>