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

ggplot2: add regression equations and R2 and adjust their positions on plot

使用 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)

我得到了这个情节

感谢@kdauria 对 this question 的回答,我在图中添加了回归方程和 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 = F)

现在,我想将回归方程和 R2 的位置调整到每个方面的特定位置(例如在每个方面的右下角“例如 0.2 y 和 0.8 x”)。

我尝试通过vjusthjust调整位置,但没有成功。

如有任何建议,我们将不胜感激。

尝试包 ggpmisc 中的 stat_poly_eq:

library(ggpmisc)
formula <- y ~ x
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", formula = formula, se = F) +
  stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), 
               label.x.npc = "right", label.y.npc = 0.15,
               formula = formula, parse = TRUE, size = 3)

returns

有关控制输出的其他选项,请参阅 ?stat_poly_eq