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

React-Plotly.js直方图:频率计算与正态分布曲线坐标获取咨询

在React-Plotly.js中为直方图添加正态分布曲线及频率计算方案

一、计算正态分布曲线的X/Y坐标

要生成匹配直方图的正态分布曲线,需先从你的filteredXRecords数据集计算核心统计参数,再生成曲线的坐标点:

  1. 计算均值与标准差
// 计算数据集均值(μ)
const mean = filteredXRecords.reduce((sum, val) => sum + val, 0) / filteredXRecords.length;

// 计算数据集标准差(σ)
const variance = filteredXRecords.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / filteredXRecords.length;
const stdDev = Math.sqrt(variance);
  1. 生成正态分布的X轴采样点
    为保证曲线平滑,生成覆盖直方图全范围的密集采样点:
const xMin = Math.min(...filteredXRecords);
const xMax = Math.max(...filteredXRecords);
// 生成200个采样点,可根据需求调整数量
const normalX = Array.from({length: 200}, (_, i) => xMin + (xMax - xMin) * i / 199);
  1. 计算正态分布的Y轴值
    由于直方图使用histnorm: 'probability'(Y轴为区间概率),需将正态分布概率密度函数的结果乘以分箱宽度,保证刻度对齐:
// 用Sturges法则估算分箱数,也可自定义
const binCount = Math.ceil(1 + 3.322 * Math.log10(filteredXRecords.length));
const binWidth = (xMax - xMin) / binCount;

// 正态分布概率密度函数
const normalPDF = (x) => (1 / (stdDev * Math.sqrt(2 * Math.PI))) * Math.exp(-Math.pow((x - mean)/stdDev, 2)/2);

// 计算对齐后的Y值
const normalY = normalX.map(x => normalPDF(x) * binWidth);

二、计算频率及频率最大值

针对histnorm: 'probability'的场景,这里的"频率"指每个分箱的概率值:

  1. 手动计算频率数组与最大值
// 初始化分箱区间与计数数组
const bins = Array.from({length: binCount}, (_, i) => xMin + i * binWidth);
const frequencyCounts = Array(binCount).fill(0);

// 统计每个分箱的样本数
filteredXRecords.forEach(val => {
  const binIndex = Math.min(Math.floor((val - xMin)/binWidth), binCount - 1);
  frequencyCounts[binIndex]++;
});

// 转换为概率(频率)
const frequencies = frequencyCounts.map(count => count / filteredXRecords.length);
// 获取频率最大值
const maxFrequency = Math.max(...frequencies);
  1. 数据量极大时的优化
    如果数据集过大,可使用流式计算法:遍历数据时仅累加总和、平方和,避免存储全部数据,最后再计算均值和方差,降低内存占用。

三、整合到现有代码

将正态分布曲线的trace加入数据数组,与直方图同图展示:

// 正态分布曲线的trace配置
const traceNormal = {
  x: normalX,
  y: normalY,
  type: 'scatter',
  mode: 'lines',
  name: '正态分布',
  line: {
    color: 'rgb(255, 0, 0)',
    width: 2
  },
  showlegend: true
};

// 合并直方图与正态曲线数据
const data = [trace1, traceNormal];

为确保分箱完全对齐,可强制指定直方图的分箱参数:

const trace1 = {
  x: filteredXRecords,
  type: "histogram",
  histnorm: 'probability',
  showlegend: true,
  marker: {
    color: 'rgb(255,255,100)',
  },
  // 强制分箱参数与手动计算一致
  xbins: {
    start: xMin,
    end: xMax,
    size: binWidth
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:45:43