繁体   English   中英

R:向 ggplot2 添加水平线

[英]R: adding horizontal lines to 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")

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM