【问题标题】:R studio add geom_abline with specified interceptR工作室添加geom_abline与指定截距
【发布时间】:2020-02-04 12:35:58
【问题描述】:

无论 x 和 y 比例是多少,我都希望有一条与图表成 45 度角的线。在这个例子中,abline 的截距应该在 x=-3 和 y=-0.5 左右。

下面几行代码:

x <- seq(1,10,1)
y <- sample(1:100, 10, replace=T)
df <- data.frame(x,y)

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_abline(slope = 45) +
  scale_y_continuous(breaks = scales::pretty_breaks(n = 10), limits = c(-10,10)) +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10), limits = c(-2,10))

【问题讨论】:

    标签: r ggplot2 rstudio


    【解决方案1】:

    你只需添加

    ggplot2::annotation_custom(grid::linesGrob())
    

    你的阴谋。

    所以你可以这样做:

    x <- rnorm(100)
    y <- rnorm(100)
    df <- data.frame(x,y)
    
    ggplot(df, aes(x=x, y=y)) +
      geom_point() +
      ggplot2::annotation_custom(grid::linesGrob())
    

    或者这个

    ggplot(df, aes(x=x)) + 
      geom_histogram() + 
      ggplot2::annotation_custom(grid::linesGrob())
    

    如果你想改变线条的外观,你需要改变 grob:

    ggplot(df, aes(x=x, y=y)) +
      geom_point() +
      ggplot2::annotation_custom(grid::linesGrob(gp = grid::gpar(col = "red", lty = 2)))
    

    【讨论】:

    • 非常感谢。这确实是我一直在寻找的> 您是否也知道如何将线用红色和虚线表示?玩了一会儿还是没搞定
    • @Jordan_b 我认为在您对linesGrob 的调用中,您会使用linesGrob(gp=gpar(col = “red”, lty = 2))
    • 非常感谢,我也安装了相关包(grid)
    • 你知道如何将线以下的部分涂成红色吗?具有一定的 alpha 值(不是全红色以便继续看到点)?
    • @Jordan_b 确保您已完成library(grid) 然后尝试将+ annotation_custom(polygonGrob(x=c(0,1,1,0), y=c(0,0,1,0), gp=gpar(fill="red", alpha=0.3))) 添加到您的情节中。更改 alpha 值以使 grob 或多或少透明
    猜你喜欢
    • 2018-01-19
    • 2015-10-28
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2015-06-02
    • 2015-03-17
    相关资源
    最近更新 更多