相关疑难解决方法(0)

在图上添加回归线方程和R2

我想知道如何添加回归线方程和R ^ 2 ggplot.我的代码是

library(ggplot2)

df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
            geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
            geom_point()
p
Run Code Online (Sandbox Code Playgroud)

任何帮助将受到高度赞赏.

r ggplot2 ggpmisc

207
推荐指数
8
解决办法
23万
查看次数

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

将回归方程、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 = …
Run Code Online (Sandbox Code Playgroud)

label r ggplot2 ggpmisc ggpubr

6
推荐指数
2
解决办法
1747
查看次数

ggplot2:添加回归方程和R2并调整它们在图上的位置

使用df和下面的代码

library(dplyr) 
library(ggplot2)
library(devtools)

df <- diamonds %>%
  dplyr::filter(cut%in%c("Fair","Ideal")) %>%
  dplyr::filter(clarity%in%c("I1" ,  "SI2" , "SI1" , "VS2" , "VS1",  "VVS2")) %>%
  dplyr::mutate(new_price = ifelse(cut == "Fair", 
                                   price* 0.5, 
                                   price * 1.1))

ggplot(df, aes(x= new_price, y= carat, color = cut))+
  geom_point(alpha = 0.3)+
  facet_wrap(~clarity, scales = "free_y")+
  geom_smooth(method = "lm", se = F)
Run Code Online (Sandbox Code Playgroud)

我有这个情节

在此输入图像描述

感谢@ kdauria对这个问题的回答,我将回归方程和R2添加到如下图中

source_gist("524eade46135f6348140")
ggplot(df, aes(x= new_price, y= carat, color = cut))+
  stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE)+
  geom_point(alpha = 0.3)+
  facet_wrap(~clarity, scales = "free_y")+
  geom_smooth(method = "lm", se …
Run Code Online (Sandbox Code Playgroud)

regression r facet ggplot2

4
推荐指数
1
解决办法
7799
查看次数

标签 统计

ggplot2 ×3

r ×3

ggpmisc ×2

facet ×1

ggpubr ×1

label ×1

regression ×1