我们能否将回归方程与 R2 和 p 值整齐对齐?

Mar*_*eal 6 label r ggplot2 ggpmisc ggpubr

将回归方程、R2 和 p 值(对于方程)巧妙地添加到ggplot图中的最佳(最简单)方法是什么?理想情况下,它应该与组和分面兼容。

第一个图具有回归方程加上使用ggpubr分组的 r2 和 p 值,但它们没有对齐?我错过了什么吗?它们可以作为一个字符串包含在内吗?

library(ggplot)
library(ggpubr)

ggplot(mtcars, aes(x = wt, y = mpg, group = cyl))+
  geom_smooth(method="lm")+
  geom_point()+
  stat_regline_equation()+
  stat_cor(aes(label = paste(..rr.label.., ..p.label.., sep = "*`,`~")),
           label.x.npc = "centre")
Run Code Online (Sandbox Code Playgroud)

情节1

这是ggpmisc 的一个选项,它做了一些奇怪的放置。
编辑奇怪的位置是由 引起的geom=text,我已将其注释掉以提供更好的位置,并添加了 `label.x = "right" 以停止过度绘制。由于@dc37 标记的上标问题,我们仍然根据ggpubr存在未对齐问题

#/sf/answers/2639618271/
library(ggpmisc)

ggplot(mtcars, aes(x = wt, y = mpg, group = cyl))+
  geom_smooth(method="lm")+
  geom_point()+
  stat_poly_eq(formula = "y~x", 
             aes(label = paste(..eq.label.., ..rr.label.., sep = "*`,`~")), 
             parse = TRUE)+
  stat_fit_glance(method = 'lm',
                  method.args = list(formula = "y~x"),
                  #geom = 'text',

                  aes(label = paste("P-value = ", signif(..p.value.., digits = 4), sep = "")))
Run Code Online (Sandbox Code Playgroud)

plot2_edited

我确实找到了一个很好的解决方案来将相关统计数据整合在一起,但这需要在 ggplot 之外创建回归,以及一堆字符串操作绒毛——这是否就这么简单?此外,它不(如当前编码)处理分组,也不会处理分面。

#/sf/answers/3638232741/
#Solution as one string, equation, R2 and p-value
lm_eqn <- function(df, y, x){
  formula = as.formula(sprintf('%s ~ %s', y, x))
  m <- lm(formula, data=df);
  # formating the values into a summary string to print out
  # ~ give some space, but equal size and comma need to be quoted
  eq <- substitute(italic(target) == a + b %.% italic(input)*","~~italic(r)^2~"="~r2*","~~p~"="~italic(pvalue), 
                   list(target = y,
                        input = x,
                        a = format(as.vector(coef(m)[1]), digits = 2), 
                        b = format(as.vector(coef(m)[2]), digits = 2), 
                        r2 = format(summary(m)$r.squared, digits = 3),
                        # getting the pvalue is painful
                        pvalue = format(summary(m)$coefficients[2,'Pr(>|t|)'], digits=1)
                   )
  )
  as.character(as.expression(eq));                 
}

ggplot(mtcars, aes(x = wt, y = mpg, group=cyl))+
  geom_point() +
  geom_text(x=3,y=30,label=lm_eqn(mtcars, 'wt','mpg'),color='red',parse=T) +
  geom_smooth(method='lm')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Ped*_*alo 6

我已经更新了 'ggpmisc' 以简化此操作。0.3.4 版本现在正在向 CRAN 发送,源代码包已上线,二进制文件应在几天内构建。

library(ggpmisc) # version >= 0.3.4 !!

ggplot(mtcars, aes(x = wt, y = mpg, group = cyl)) +
  geom_smooth(method="lm")+
  geom_point()+
  stat_poly_eq(formula = y ~ x, 
               aes(label = paste(..eq.label.., ..rr.label.., ..p.value.label.., sep = "*`,`~")), 
               parse = TRUE,
               label.x.npc = "right",
               vstep = 0.05) # sets vertical spacing
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


dc3*_*c37 5

一个可能的解决方案是通过传递to和或toggpubr将方程公式和 R2 值放在图表的顶部(取决于您是否希望将其放在图的右侧或左侧)Inflabel.yInf-Inflabel.x

vjust由于 R 上的上标 2,两个文本都不会对齐。因此,您必须使用和来稍微调整它,hjust以便对齐两个文本。

然后,它甚至可以处理不同比例的多面图。

library(ggplot)
library(ggpubr)

ggplot(mtcars, aes(x = wt, y = mpg, group = cyl))+
  geom_smooth(method="lm")+
  geom_point()+
  stat_regline_equation(label.x = -Inf, label.y = Inf, vjust = 1.5, hjust = -0.1, size = 3)+
  stat_cor(aes(label = paste(..rr.label.., ..p.label.., sep = "*`,`~")),
           label.y= Inf, label.x = Inf, vjust = 1, hjust = 1.1, size = 3)+
  facet_wrap(~cyl, scales = "free")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

它回答了你的问题吗?


编辑:通过手动添加方程来替代

正如您的类似问题中所述(Label ggplot groups usingequation with ggpmisc),您可以通过将文本传递为以下方式来添加方程geom_text

df_mtcars <- mtcars %>% mutate(factor_cyl = as.factor(cyl))

df_label <- df_mtcars %>% group_by(factor_cyl) %>%
  summarise(Inter = lm(mpg~wt)$coefficients[1],
            Coeff = lm(mpg~wt)$coefficients[2],
            pval = summary(lm(mpg~wt))$coefficients[2,4],
            r2 = summary(lm(mpg~wt))$r.squared) %>% ungroup() %>%
  #mutate(ypos = max(df_mtcars$mpg)*(1-0.05*row_number())) %>%
  #mutate(Label2 = paste(factor_cyl,"~Cylinders:~", "italic(y)==",round(Inter,3),ifelse(Coeff <0,"-","+"),round(abs(Coeff),3),"~italic(x)",sep ="")) %>%
  mutate(Label = paste("italic(y)==",round(Inter,3),ifelse(Coeff <0,"-","+"),round(abs(Coeff),3),"~italic(x)",
                       "~~~~italic(R^2)==",round(r2,3),"~~italic(p)==",round(pval,3),sep =""))

# A tibble: 3 x 6
  factor_cyl Inter Coeff   pval    r2 Label                                                                    
  <fct>      <dbl> <dbl>  <dbl> <dbl> <chr>                                                                    
1 4           39.6 -5.65 0.0137 0.509 italic(y)==39.571-5.647~italic(x)~~~~italic(R^2)==0.509~~italic(p)==0.014
2 6           28.4 -2.78 0.0918 0.465 italic(y)==28.409-2.78~italic(x)~~~~italic(R^2)==0.465~~italic(p)==0.092 
3 8           23.9 -2.19 0.0118 0.423 italic(y)==23.868-2.192~italic(x)~~~~italic(R^2)==0.423~~italic(p)==0.012
Run Code Online (Sandbox Code Playgroud)

您可以将其用于geom_text以下用途:

ggplot(df_mtcars,aes(x = wt, y = mpg, group = factor_cyl, colour= factor_cyl))+
  geom_smooth(method="lm")+
  geom_point()+
  geom_text(data = df_label,
            aes(x = -Inf, y = Inf, 
                label = Label, color = factor_cyl), 
          show.legend = FALSE, parse = TRUE, size = 3,vjust = 1, hjust = 0)+
  facet_wrap(~factor_cyl)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

至少解决了R上标2导致的错位问题。