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

R语言绘制多幅双变量图时如何调小间距且保留边缘轴标签

你之前用mar=rep(2,4)出现轴标签异常,是因为统一设置2个单位的边距不足以容纳轴标签内容,直接被绘图区域截断了。我们可以通过分位置设置边距 + 按需显示轴标签的方式实现需求,既能缩小子图间距,又能完整保留需要的标签。

方案1:精准控制不同位置子图的边距(推荐)

可以根据子图所处的行列位置,单独设置对应方向的边距,仅给需要显示标签的边缘留足空间:

op <- par(mfrow = c(3,2), mgp = c(2, 0.8, 0)) # mgp调整轴元素间距,进一步节省空间
plot_idx <- 1 # 记录当前是第几个子图,3行2列按行排序共6个

for (z in c("CER", "clustSize", "nonZero")) {
  # 左列子图:alpha为x轴
  par(mar = case_when(
    plot_idx %in% c(1,3) ~ c(1,3,1,1), # 左列非底部:左留3放y标签,其他边距最小
    plot_idx ==5 ~ c(3,3,1,1), # 左列底部:下留3放x标签,左留3放y标签
    TRUE ~ c(1,1,1,1)
  ))
  f <- factor(res$L1)
  plot(res[,z] ~ alpha, data=res, 
       ylab = if(plot_idx %%2 ==1) z else "", # 仅左列显示y标签
       xlab = if(plot_idx >=5) "alpha" else "", # 仅底部行显示x标签
       col=f)
  for (y in res$L1) {
    sres <- subset(res, L1==y)
    lines(sres$alpha, sres[,z], col=match(y, levels(f)))
  }
  plot_idx <- plot_idx +1
  
  # 右列子图:L1为x轴
  par(mar = if(plot_idx %in% c(2,4)) c(1,1,1,1) else c(3,1,1,1))
  f <- factor(res$alpha)
  plot(res[,z] ~ L1, data=res, 
       ylab = "", # 右列不显示y标签
       xlab = if(plot_idx >=5) "L1" else "", # 仅底部行显示x标签
       col=f)
  for (y in res$alpha) {
    sres <- subset(res, alpha==y)
    lines(sres$L1, sres[,z], col=match(y, levels(f)))
  }
  plot_idx <- plot_idx +1
}
par(op)

mar的四个值依次为c(下边距, 左边距, 上边距, 右边距),单位为行高,仅给需要显示标签的边缘留3个单位空间,其他边缘只留1个单位,可最大程度缩小子图间距。


方案2:外边缘+统一小边距(代码更简洁)

如果不需要完全隐藏非边缘子图的轴标签,也可以通过设置整体外边缘oma,配合内部子图统一小边距实现:

op <- par(mfrow = c(3,2), 
          mar = c(2,2,1,1), # 内部子图统一小边距
          oma = c(2,2,0,0), # 整体外边缘预留空间放标签
          mgp = c(2,0.7,0)) # 缩小轴元素间距适配小边距

for (z in c("CER", "clustSize", "nonZero")) {
  f <- factor(res$L1)
  plot(res[,z] ~ alpha, data=res, ylab=z, col=f)
  for (y in res$L1) {
    sres <- subset(res, L1==y)
    lines(sres$alpha, sres[,z], col=match(y, levels(f)))
  }
  
  f <- factor(res$alpha)
  plot(res[,z] ~ L1, data=res, ylab=z, col=f)
  for (y in res$alpha) {
    sres <- subset(res, alpha==y)
    lines(sres$L1, sres[,z], col=match(y, levels(f)))
  }
}
par(op)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:57:04