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

如何调整效应图的面板顺序与分栏文本?

问题解决:调整效应图面板顺序与分栏文本

问题描述

使用effects包绘制多国家的年龄效应图时,遇到两个问题:

  1. 想将面板顺序调整为瑞典、挪威、澳大利亚、美国,尝试index.cond=list(c("Sweden", "Norway", "Australia", "USA"))无效;
  2. 想将分栏文本从country=Sweden改为仅显示Sweden,尝试strip = strip.custom(strip.names=FALSE, strip.levels=TRUE)无效。

原代码:

# data for WVS is in the package
library(MASS) 
library(effects)
wvs.2 <- polr(poverty ~ country*(gender + religion + degree + ns(age, 4)),data = WVS)  

#effect plot
plot(Effect(focal.predictors = c("country","age"), mod = wvs.2, 
          xlevels = list(age = 20:80),
          latent = TRUE),
   rug = FALSE,
   ylim = c(0,3.5))

解决方案

1. 调整面板顺序

index.cond参数在effects的plot方法中不直接生效,核心是要先修改country变量的因子水平顺序,让效应对象生成时就遵循指定顺序:

方法1:拟合模型前重排因子水平

在拟合polr模型前,重新设定country的因子水平:

library(MASS) 
library(effects)

# 重排country的因子水平为目标顺序
WVS$country <- factor(WVS$country, levels = c("Sweden", "Norway", "Australia", "USA"))

# 重新拟合模型
wvs.2 <- polr(poverty ~ country*(gender + religion + degree + ns(age, 4)),data = WVS)  

# 绘制效应图,此时面板顺序已按设定排列
plot(Effect(focal.predictors = c("country","age"), mod = wvs.2, 
          xlevels = list(age = 20:80),
          latent = TRUE),
   rug = FALSE,
   ylim = c(0,3.5))

方法2:生成效应对象时指定顺序

如果不想修改原始数据,可在生成效应对象时直接指定country的顺序:

eff_obj <- Effect(focal.predictors = c("country","age"), mod = wvs.2, 
                  xlevels = list(age = 20:80, 
                                 country = c("Sweden", "Norway", "Australia", "USA")),
                  latent = TRUE)
plot(eff_obj, rug = FALSE, ylim = c(0,3.5))

2. 修改分栏文本(移除country=前缀)

effects的plot方法基于lattice,需正确传递strip参数或修改效应对象标签:

方法1:传递自定义strip函数

在plot函数中直接定义strip函数,隐藏变量名:

plot(eff_obj, rug = FALSE, ylim = c(0,3.5),
     strip = function(...) strip.default(..., strip.names = FALSE))

方法2:修改效应对象的条件标签

直接调整效应对象的标签属性:

# 获取当前条件标签
current_labels <- eff_obj$variables$country$levels
# 直接赋值为纯净的国家名称(若原标签带前缀,可使用gsub("country=", "", current_labels)移除)
eff_obj$variables$country$levels <- current_labels

# 绘图
plot(eff_obj, rug = FALSE, ylim = c(0,3.5))

完整代码示例

library(MASS) 
library(effects)

# 重排country因子水平
WVS$country <- factor(WVS$country, levels = c("Sweden", "Norway", "Australia", "USA"))

# 拟合模型
wvs.2 <- polr(poverty ~ country*(gender + religion + degree + ns(age, 4)),data = WVS)  

# 生成效应对象
eff_obj <- Effect(focal.predictors = c("country","age"), mod = wvs.2, 
                  xlevels = list(age = 20:80),
                  latent = TRUE)

# 绘图:调整顺序+修改分栏文本
plot(eff_obj, rug = FALSE, ylim = c(0,3.5),
     strip = function(...) strip.default(..., strip.names = FALSE))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:46:05