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

R语言配对图(pairs plot)直方图拟合密度曲线失效问题

R语言配对图(pairs plot)直方图添加密度曲线不显示问题解决

问题根源

自定义的panel.hist函数中,已将直方图高度通过y = y/max(y)做了01区间的归一化处理,同时将面板y轴可视范围固定为01.5。而lines(density(x))输出的y值为原始概率密度值,数值范围和归一化后的y轴不匹配,导致曲线被绘制到可视区域外,因此无法显示。

修复后代码

# 自定义对角线面板函数:直方图+归一化密度曲线
panel.hist = function(x, ...) {
  usr = par("usr"); on.exit(par(usr))
  par(usr = c(usr[1:2], 0, 1.5))
  h = hist(x, plot = FALSE, freq = FALSE, na.rm = TRUE) 
  breaks = h$breaks; nB = length(breaks)
  # 直方图高度归一化到0-1区间
  y_hist = h$density
  y_hist_norm = y_hist / max(y_hist)
  rect(breaks[-nB], 0, breaks[-1], y_hist_norm, col = "cyan", ...)
  # 密度曲线同步做归一化处理,匹配直方图y轴范围
  dens = density(x, na.rm = TRUE)
  dens$y = dens$y / max(y_hist)
  lines(dens, col = "darkred", lwd = 1.5)
}
# 绘制配对图
pairs(squid[, c("DML", "weight", "eviscerate.weight", "ovary.weight", "nid.length", "nid.weight")], 
      upper.panel = panel.smooth, 
      diag.panel = panel.hist, 
      lower.panel = panel.cor)

可选调整项

  • 可修改lines()函数中的col(颜色)、lwd(线宽)、lty(线型)参数,自定义密度曲线样式
  • 若需要展示原始概率密度刻度,可删除归一化逻辑,将y轴上限修改为适配密度最大值的数值:将par(usr = c(usr[1:2], 0, 1.5))替换为par(usr = c(usr[1:2], 0, max(h$density)*1.2)),同时将直方图绘制的y值替换为原始密度值h$density即可
  • 若运行时提示panel.cor未找到,需提前定义该自定义函数(该函数通常用于绘制下三角面板的相关系数)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:15:02