如何自定义effects包绘制的交互效应图面板标题?
自定义effects包交互效应图的面板标题
我用effects包绘制了交互作用的效应图,想自定义面板标题(当前显示的是“education = College”这类格式),尝试过两种方法但都失败了:
- 把变量重命名为
Educational Level,但空格导致报错:
Error in parse(text = paste("~", paste(extras, collapse = "+"))) :
:1:28: unexpected symbol
- 在
plot/allEffects函数里试了panel.title等参数,但找不到能修改该部分的参数。
方法一:修改因子水平标签(推荐)
不用改动变量名,直接给education因子的水平设置自定义标签,效应图的面板标题会自动使用新标签:
# 生成数据时直接设置因子标签 set.seed(123) education <- factor(rep(c("High School", "College", "Graduate"), each = 30), labels = c("高中", "大学", "研究生")) # 替换成你需要的自定义标题 study_hours <- rep(c(10, 20, 30), each = 10, times = 3) exam_scores <- rnorm(90, mean = 70, sd = 10) example_df <- data.frame(education, study_hours, exam_scores) # 后续建模和绘图步骤不变 library(glmmTMB) models_example <- glmmTMB(exam_scores ~ education * study_hours, data = example_df) library(effects) effects_plot_example <- plot(allEffects(models_example, data = example_df)) print(effects_plot_example)
如果已经有现成的数据框,也可以事后修改因子标签:
example_df$education <- factor(example_df$education, labels = c("高中", "大学", "研究生"))
方法二:直接修改效应图对象的标题文本
如果不想改动原始数据,可以先让plot()返回图形对象列表,再逐个修改面板标题:
# 生成效应图对象但不直接绘图 effects_plot_example <- plot(allEffects(models_example, data = example_df), plot = FALSE) # 定义新的面板标题 new_titles <- c("教育水平:高中", "教育水平:大学", "教育水平:研究生") # 遍历替换每个子图的标题 for(i in seq_along(effects_plot_example)){ effects_plot_example[[i]]$main <- new_titles[i] } # 绘制修改后的图 plot(effects_plot_example)
内容的提问来源于stack exchange,提问作者ihecker
相关产品推荐
相关产品推荐

