繁体   English   中英

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对这个问题的回答,我将回归方程和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 ,但没有奏效。

任何建议都将受到高度赞赏。

尝试stat_poly_eq从包ggpmisc

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM