r - ggpairs,按组颜色但单一回归线

标签 r ggplot2 ggpairs

鉴于以下 ggpairs 绘图:

data(iris)
ggpairs(iris[1:4],
        lower=list(
          mapping = aes(color=iris$Species),
          continuous = wrap("points", size=0.7)
          )
        )

结果是:
enter image description here

如何将单个回归线添加到每个散点图,而不将回归线也映射到分组,就像添加 continuous = wrap("smooth") 时会发生的情况?

我希望这些点按组着色,但整体上 x 和 y 变量之间关系的回归线。

我不知道将 aes 映射放置在哪里,以便它只影响“点”而不影响“平滑”。

最佳答案

如果您想要像这样的专门绘图,您需要创建自己的函数。它必须采用特定格式,采用 datamapping... 参数,并根据这些参数创建 ggplot:

library(GGally)

my_func <- function(data, mapping, ...) {
  
    ggplot(data, mapping) + 
      geom_point(size = 0.7) +
      geom_smooth(formula = y~x, method = loess, color = "black")
  }

ggpairs(iris[1:4],
        lower=list(
          mapping = aes(color=iris$Species),
          continuous = my_func
          )
        )

enter image description here

如果您正在寻找直线回归线,则只需根据需要修改 my_func 即可。例如,

my_func <- function(data, mapping, ...) {
  
    ggplot(data, mapping) + 
      geom_point(size = 0.7) +
      geom_smooth(formula = y~x, method = lm, color = "black", se = FALSE,
                  linetype = 2)
  }

给你:

enter image description here

关于r - ggpairs,按组颜色但单一回归线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72152164/

相关文章:

javascript - Shiny 模块和 renderUI 传递 javascript 代码

r - ggplot 未显示所有 x 轴刻度

python - 从 python 中的数据框中创建两列的 python 对列表

r - 条形图上的 ggpairs 标签

r - 聚合值和缺失值

r - 为什么调用指定命名空间的函数会更慢?

r - scale_fill_manual定义NA值的颜色

r - 如何在 ggpairs (R) 中显示带有 scale_colour_manual 的彩色组相关性?

r - 如何在Rmarkdown Beamer Madrid演示文稿中结束 header 3框?

r - ggplot2中的饼图具有可变的饼图大小