R语言plot(effect())无法用par()改轴标签大小及axes参数报错问题
嘿,我来帮你解决这两个问题!首先得搞清楚你是用什么函数绘制交互效应图的——不同绘图系统(base R、ggplot2、emmeans/effects这类统计绘图包)的参数逻辑完全不一样,这就是你踩坑的核心原因。下面分两种最常见的场景给你解决方案:
场景1:用emmeans包画交互图(统计圈最常用的交互效应可视化工具)
如果你是用emmeans的plot()函数生成图,那par()的设置肯定没用,因为它底层默认用的是ggplot2或者lattice绘图系统,根本不吃base R的par()参数;另外axes=FALSE也不是它的合法参数,这就是你报错的原因。
解决办法:
调整轴标签/刻度大小:直接用对应绘图系统的参数设置,不用
par():
如果你的emmeans输出是ggplot风格(现在默认都是),直接加theme()就行:library(emmeans) # 先拟合交互模型 model <- lm(weight ~ group * gender, data = 你的数据集) # 提取交互效应的边际均值 emm <- emmeans(model, ~ group * gender) # 绘图+调整轴属性 plot(emm, type = "response") + theme(axis.title = element_text(size = 16), # 轴标签放大到16号 axis.text = element_text(size = 14)) # 轴刻度文字放大到14号要是你的
emmeans用的是lattice风格(老版本可能这样),就用par.settings:plot(emm, type = "response", par.settings = list(axis.text = list(cex = 1.4), # 刻度放大1.4倍 axis.components = list(main = list(cex = 1.6)))) # 标签放大1.6倍隐藏坐标轴不报错:别用
axes=FALSE,改用对应系统的方法:
ggplot版直接在theme()里把轴相关元素设为空:plot(emm, type = "response") + theme(axis.line = element_blank(), axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank())lattice版就加
scales = list(draw = FALSE):plot(emm, type = "response", scales = list(draw = FALSE))
场景2:用base R手动画交互图
如果是自己用plot()、lines()这类base R函数手动绘图,那par()的设置要先于绘图命令才会生效;另外报错的原因大概率是你把axes=FALSE传给了不接受它的函数(比如模型拟合函数或者其他统计函数),得把它加在plot()里才行。
解决办法:
让
par()设置生效:先调全局参数,再绘图:# 先设置全局绘图参数,mar是边距,避免标签被截断 par(cex.lab = 2, cex.axis = 2, mar = c(5,5,2,2)) # 先按group和gender分组算体重均值(方便绘图) mean_weight <- aggregate(weight ~ group + gender, data = 你的数据集, mean) # 先画男性组的线 plot(mean_weight$group[mean_weight$gender==1], mean_weight$weight[mean_weight$gender==1], type = "l", lwd = 2, col = "blue", xlab = "分组", ylab = "体重", xlim = c(1,2), ylim = range(mean_weight$weight)) # 再加女性组的线 lines(mean_weight$group[mean_weight$gender==2], mean_weight$weight[mean_weight$gender==2], type = "l", lwd = 2, col = "red") # 加个图例 legend("topright", legend = c("男性", "女性"), col = c("blue", "red"), lwd = 2)这样
cex.lab和cex.axis就会乖乖生效了~隐藏坐标轴不报错:把
axes=FALSE直接加在base R的plot()函数里:par(cex.lab = 2, cex.axis = 2) plot(mean_weight$group[mean_weight$gender==1], mean_weight$weight[mean_weight$gender==1], type = "l", lwd = 2, col = "blue", xlab = "分组", ylab = "体重", xlim = c(1,2), ylim = range(mean_weight$weight), axes = FALSE) # 这里加才是对的! # 要是之后想手动加轴,用axis()就行 axis(1, at = c(1,2), labels = c("吸烟组", "对照组"), cex.axis = 2) axis(2, cex.axis = 2) box() # 加个边框更美观
敲黑板划重点!
- 别搞混绘图系统:base R用
par(),ggplot2用theme(),lattice用par.settings,跨系统用参数肯定没用。 - 参数要传给对的函数:
axes=FALSE是base Rplot()的参数,别传给模型或者emmeans这类统计函数,不然肯定报错。
内容的提问来源于stack exchange,提问作者GY.Zhao

