如何用ggpairs获得R ^ 2? [英] How to get R^2 with ggpairs?

查看:60
本文介绍了如何用ggpairs获得R ^ 2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使 ggpairs 用R ^ 2而不是相关性报告上角?

How to make ggpairs report the upper corner with R^2 instead of correlation?

library(GGally)    
ggpairs(mtcars[c("mpg", "disp", "hp", "drat", "wt", "qsec")])

推荐答案

我认为您需要编写一个自定义函数,如下所示.(这种方法的一个警告是,与相关性不同,r ^ 2假定一个因变量,因此可能不明智.)

I think that you will need to write a custom function, shown below. (One caveat to this approach is that different to correlation the r^2 assumes a dependent variable so this may not be sensible).

library(GGally) # version 1.5.0

lm_fun <- function(data, mapping, ndp=2, ...){

    # Extract the relevant columns as data
    x <- eval_data_col(data, mapping$x)
    y <- eval_data_col(data, mapping$y)

    # Calculate the r^2 & format output
    m <- summary(lm(y ~ x))
    lbl <- paste("r^2: ", formatC(m$r.squared, digits=ndp, format="f"))

    # Write out label which is centered at x&y position
    ggplot(data=data, mapping=mapping) + 
      annotate("text", x=mean(x, na.rm=TRUE), y=mean(y, na.rm=TRUE), label=lbl, parse=TRUE, ...)+
      theme(panel.grid = element_blank()) 
  }

# Call
ggpairs(mtcars[c("mpg", "disp", "hp", "drat", "wt", "qsec")], 
        upper=list(continuous=lm_fun))

编辑:您能帮忙解释一下如何在r ^ 2和值之间的lbl中添加新行吗?

EDIT: Can you please help to explain how to add a new line into the lbl between r^2 and the value?

您可以通过将相关代码更改为以下任意一种来使用 atop :

You can use atop by changing the relevant code to either:

lbl <- substitute(atop(~r^2*':', v), 
                  list(v=formatC(m$r.squared, digits=ndp, format="f")))

 v <- formatC(m$r.squared, digits=ndp, format="f")
 lbl <- bquote(atop(~r^2*':', .(v))) 

然后您需要调整 annotate 调用以正确解析标签

You then need to tweak the annotate call to correctly parse the label

annotate("text", x=mean(x, na.rm=TRUE), y=mean(y, na.rm=TRUE), 
          label=deparse(lbl), parse=TRUE, hjust=0, ...)

我添加了 just = 0 ,以尝试使文本左对齐,但效果不佳.

I added hjust=0 in an attempt to left-align the text but this hasn't quite worked.

这篇关于如何用ggpairs获得R ^ 2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆