【问题标题】:R: adding horizontal lines to ggplot2R:向ggplot2添加水平线
【发布时间】:2021-05-13 04:51:24
【问题描述】:

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

谢谢

【问题讨论】:

  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example
  • 您的代码中有一些拼写错误:忘记了) - 它似乎适用于上面的编辑。正如@Ronak Shah 所建议的,如果 MRE 仍然无法按您的意愿工作,请提供它
  • geom_hline(yintercept = mean(var2))?

标签: r ggplot2 data-visualization


【解决方案1】:

确实有可能:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多