R:向 ggplot2 添加水平线

时间:2021-05-13 04:51:24

标签: r ggplot2 data-visualization

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

谢谢

1 个答案:

答案 0 :(得分:5)

确实有可能:

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

相关问题