【问题标题】:ggplot2: add regression equations and R2 and adjust their positions on plotggplot2:添加回归方程和 R2 并调整它们在绘图上的位置
【发布时间】:2016-09-26 11:19:10
【问题描述】:

使用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调整位置,但没有成功。

任何建议将不胜感激。

【问题讨论】:

    标签: r ggplot2 regression facet


    【解决方案1】:

    从包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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 2020-11-10
    • 2018-06-19
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    相关资源
    最近更新 更多