【问题标题】:Highlight highest residuals in a plot: R突出显示图中的最高残差:R
【发布时间】:2020-09-03 22:36:10
【问题描述】:

我正在尝试学习如何在图表中突出显示和注释某些点。出于可重现示例的目的,我使用的是 alr4 包中的 UBSprices 数据集。

我正在画一条 ols 线和一条 y=x 线。我想突出显示和注释离 OLS 线最远的点(即最高残差)。

到目前为止,这是我的代码:

ggplot(UBSprices, aes(x = bigmac2003, y = bigmac2009)) + geom_point() + geom_smooth(method = "lm", se = FALSE) + 
  geom_abline(color = "green", size = 1) + coord_fixed()

【问题讨论】:

    标签: r ggplot2 dplyr linear-regression


    【解决方案1】:

    您可以计算残差,然后确定绝对值大于某个截止分位数的残差。例如:

    library(tidyverse)
    library(alr4)
    
    UBSprices %>% 
      mutate(resid = resid(lm(bigmac2009 ~ bigmac2003, data = .)),
             mark = abs(resid) >= quantile(abs(resid), prob=0.9)) %>% 
      ggplot(aes(x = bigmac2003, y = bigmac2009)) + 
      geom_point(aes(colour=mark), show.legend=FALSE) + 
      geom_smooth(method = "lm", se = FALSE) + 
      geom_abline(color = "green", size = 1) + 
      coord_fixed() +
      theme_bw() +
      scale_colour_manual(values=c("blue", "red"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      相关资源
      最近更新 更多