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

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

我得到了这个情节。

enter image description here

感谢@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 = F)

enter image description here

现在,我希望将回归方程和R2的位置调整到每个分面的特定位置(例如,在每个分面的右下角,如“0.2 y和0.8 x”)。我尝试通过vjusthjust来调整位置,但没有成功。非常感谢您提供任何建议。
1个回答

11
尝试使用包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)

返回

这里输入图片描述

查看?stat_poly_eq以了解其他控制输出的选项。


请参见ggpmisc包的作者在ggplot2:添加回归线方程和R2图答案以获取更多详细信息或联系作者。 - Uwe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接