ggplot2:添加回归方程和R2并调整其在绘图上的位置 [英] ggplot2: add regression equations and R2 and adjust their positions on plot

查看:848
本文介绍了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)

我有这个情节

感谢@kdauria对此问题的回答,我在图表中添加了回归方程式和R2,如下所示:

Thanks to @kdauria's answer to this question, I added regression equations and R2 to the plot as below

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").

Now, I want to adjust the position of the regression equations and R2 to be at a specific place in each of the facets (for example at the bottom right in each facet "e.g. 0.2 y and 0.8 x).

我尝试通过vjusthjust调整位置,但是没有用.

I tried to adjust the position through vjust and hjust but it didn't work.

任何建议将不胜感激.

Any suggestions would be highly appreciated.

推荐答案

从软件包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.

See ?stat_poly_eq for other options to control the output.

这篇关于ggplot2:添加回归方程和R2并调整其在绘图上的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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