【问题标题】:How can a graph of a polynomial regression with a categorical variable be plotted?如何绘制具有分类变量的多项式回归图?
【发布时间】:2021-12-20 10:26:16
【问题描述】:

在 R 统计包中,有没有办法用一个连续变量和一个分类变量绘制二阶多项式回归图?

要生成具有一个分类变量的线性回归图:

library(ggplot2)
library(ggthemes) ## theme_few()
set.seed(1)
df <- data.frame(minutes = runif(60, 5, 15), endtime=60, category="a")
df$category = df$category=letters[seq( from = 1, to = 2 )]
df$endtime = df$endtime + df$minutes^3/180 + df$minutes*runif(60, 1, 2)
ggplot(df, aes(y=endtime, x=minutes, col = category)) +
  geom_point() +
  geom_smooth(method=lm) + 
  theme_few()

绘制具有一个连续变量的多项式图:

 ggplot(df, aes(x=minutes, y=endtime)) +    
        geom_point() +           
        stat_smooth(method='lm', formula = y ~ poly(x,2), size = 1) + 
        xlab('Minutes of warm up') +
        ylab('End time')

但我不知道如何绘制一个包含一个连续变量和一个分类变量的多项式图。

【问题讨论】:

    标签: r ggplot2 regression


    【解决方案1】:

    只需添加colourgroup 映射。这将使 ggplot 适合并显示每个类别的单独多项式回归。 (1) 无法显示加法混合多项式回归(即lm(y ~ poly(x,2) + category)); (2) 此处显示的内容与交互模型lm(y ~ poly(x,2)*col) 的结果完全 不相等,因为每个组的残差方差(以及因此置信带的宽度)都是单独估计的。

    ggplot(df, aes(x=minutes, y=endtime, col = category)) +    
      geom_point() +           
      stat_smooth(method='lm', formula = y ~ poly(x,2)) + 
      labs(x = 'Minutes of warm up', y = 'End time') +
      theme_few()
    

    【讨论】:

    • 谢谢 Ben,您的解决方案和 cmets 非常有帮助。
    猜你喜欢
    • 2018-02-06
    • 2019-12-21
    • 2021-08-31
    • 2023-03-15
    • 2017-12-14
    • 2023-01-17
    • 1970-01-01
    • 2011-02-09
    相关资源
    最近更新 更多