如何可视化ordinal包有序回归中response*temp交互项的斜率?
有序回归交互项斜率的可视化方案
我用ordinal包拟合了包含response*temp交互项的有序回归模型,已经提取出response:tempcold(0.14)和response:tempwarm(-0.01)的斜率估计值,但不知道怎么以有序结果变量为y轴来可视化这些斜率。相关代码和模型结果如下:
library(ordinal) wine2 <- wine wine2$rating[wine2$rating==5] <- 1 wine2$rating <- ordered(wine2$rating) fm1 <- clm(rating ~ response*temp, data=wine2) summary(fm1)
模型输出:
Coefficients: Estimate Std. Error z value Pr(>|z|) response 0.14478 0.02965 4.883 1.04e-06 *** tempwarm 6.89043 1.78282 3.865 0.000111 *** response:tempwarm -0.15651 0.03874 -4.040 5.34e-05 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Threshold coefficients: Estimate Std. Error z value 1|2 3.389 1.022 3.317 2|3 5.610 1.171 4.789 3|4 7.830 1.294 6.053
可视化思路与代码
有序回归的系数对应的是**潜变量(潜在响应变量)**的斜率,直接对应你提取的数值。如果要关联到有序因变量的类别,有两种常用方式:
方式1:直接展示潜变量随response的变化(对应斜率)
这种方式能直接呈现你提取的两个斜率,潜变量的变化斜率就是response在不同temp组的系数:
library(ggplot2) # 创建覆盖response全范围的预测网格 pred_grid <- expand.grid( response = seq(min(wine2$response), max(wine2$response), length.out = 100), temp = c("cold", "warm") ) # 预测潜变量值(线性预测器结果) pred_grid$latent <- predict(fm1, newdata = pred_grid, type = "linear.predictor") # 绘图 ggplot(pred_grid, aes(x = response, y = latent, color = temp)) + geom_line(linewidth = 1) + labs(x = "Response", y = "潜在响应变量", color = "温度") + theme_minimal()
图中两条线的斜率就是你提取的0.14(cold组)和-0.01(warm组),能直观对比不同温度下response对潜变量的影响方向和大小。
方式2:展示各有序类别概率随response的变化
这种方式更贴合有序因变量的实际意义,能看到response变化时,每个rating等级的概率如何随温度分组变化:
library(tidyr) # 创建包含所有rating等级的预测网格 pred_grid <- expand.grid( response = seq(min(wine2$response), max(wine2$response), length.out = 100), temp = c("cold", "warm"), rating = levels(wine2$rating) ) # 预测每个类别的概率 pred_probs <- predict(fm1, newdata = pred_grid, type = "prob") pred_grid <- cbind(pred_grid, pred_probs) # 转换为长格式数据 pred_grid_long <- pivot_longer(pred_grid, cols = starts_with("1"), names_to = "rating_level", values_to = "probability") pred_grid_long$rating_level <- ordered(pred_grid_long$rating_level, levels = levels(wine2$rating)) # 绘图 ggplot(pred_grid_long, aes(x = response, y = probability, color = temp)) + geom_line(linewidth = 0.8) + facet_wrap(~rating_level) + labs(x = "Response", y = "预测概率", color = "温度") + theme_minimal()
通过这个图,你能清晰看到在cold和warm温度下,response变化时各个rating等级的概率升降趋势,间接体现两个斜率的实际影响。
内容的提问来源于stack exchange,提问作者locus
相关产品推荐
相关产品推荐

