You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:如何使用Effects包仅绘制多项回归模型的指定类别

只绘制多项回归模型中单一类别的效应图(Effects包)

要在Effects包中仅绘制Versicolor类别的效应图,你可以通过两种简单的方法实现:

方法1:使用plot()函数的select参数

这是最直接的方式,无需修改原始的effect对象,只需在调用plot()时指定要显示的类别索引或名称即可:

library(nnet)
library(effects)

# 拟合多项回归模型
m1 <- multinom(Species ~ Sepal.Width * Petal.Width + Sepal.Length, data = iris)

# 生成效应对象
plt <- effect("Sepal.Width * Petal.Width", m1, x.var = "Sepal.Width")

# 仅绘制Versicolor类别(它是响应变量的第2个级别,顺序对应iris$Species的默认水平)
plot(plt, x.var = "Sepal.Width", 
     select = 2,  # 指定第2个类别,即Versicolor
     lattice = list(strip = list(factor.names = F)), 
     confint = list(style="auto", col = "black"), 
     axes = list(grid = T, x = list(rug = F)))

如果你不确定类别的索引,也可以直接用类别名称指定(注意大小写要匹配):

plot(plt, x.var = "Sepal.Width", 
     select = "Versicolor",
     lattice = list(strip = list(factor.names = F)), 
     confint = list(style="auto", col = "black"), 
     axes = list(grid = T, x = list(rug = F)))

方法2:手动筛选Effect对象的内容

如果你需要单独保存某一类别的效应对象,可以手动提取对应类别的拟合值、置信区间等信息,创建一个新的Effect对象:

# 找到Versicolor对应的列索引
versicolor_col <- which(colnames(plt$fit) == "Versicolor")

# 创建仅包含Versicolor的新Effect对象
plt_versicolor <- plt
plt_versicolor$fit <- plt$fit[, versicolor_col, drop = FALSE]
plt_versicolor$lower <- plt$lower[, versicolor_col, drop = FALSE]
plt_versicolor$upper <- plt$upper[, versicolor_col, drop = FALSE]
plt_versicolor$response.levels <- plt$response.levels[versicolor_col]
plt_versicolor$n.levels <- 1  # 更新类别数量为1

# 绘制新的效应图
plot(plt_versicolor, x.var = "Sepal.Width", 
     lattice = list(strip = list(factor.names = F)), 
     confint = list(style="auto", col = "black"), 
     axes = list(grid = T, x = list(rug = F)))

为什么之前的layout参数没用?

你尝试的layout参数是用来控制多面板图的排列方式,它只能调整已有面板的布局,无法筛选要显示的类别。而select参数才是专门用来指定要展示的响应类别的参数,完全匹配你的需求。

内容的提问来源于stack exchange,提问作者Ttytamaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 21:57:43