双Y轴概率直方图与累积概率曲线缩放异常问题求助
解决累积概率Y轴缩放错误的思路
核心问题定位
你的问题大概率是累积概率未做归一化,或者双Y轴的缩放逻辑没对齐。以下是具体排查和修复步骤:
1. 确保累积概率是归一化后的结果
如果直接对直方图的bin计数做累加,得到的是累计样本数量(最终等于总样本数),必须除以总样本数才能得到0-1范围的概率值:
# 假设你的模拟结果存在simulation_results变量中 total_samples = len(simulation_results) # 绘制直方图并获取bin计数和区间 counts, bins, patches = ax1.hist(simulation_results, bins=30) # 计算归一化后的累积概率 cumulative_prob = np.cumsum(counts) / total_samples
2. 强制对齐双Y轴的范围
绘制累积概率曲线后,手动设置第二个Y轴的范围为0到1,避免matplotlib自动缩放导致的异常:
ax2.plot(bins[:-1], cumulative_prob, color='red') ax2.set_ylim(0, 1) # 关键:强制Y轴2的范围为0-1 ax2.set_ylabel('累积概率')
3. 保证直方图与累积计算的bins一致
如果你的代码中是分别定义直方图的bins和累积计算的bins,很可能出现区间不匹配的问题。必须基于直方图返回的bins来计算累积概率,不要单独重新定义bins参数。
完整修复示例片段
import numpy as np import matplotlib.pyplot as plt def plot_risk_histogram(simulation_results): fig, ax1 = plt.subplots() # 绘制主直方图(Y轴1:Bin Count) total_samples = len(simulation_results) counts, bins, patches = ax1.hist(simulation_results, bins=30, alpha=0.7) ax1.set_ylabel('Bin Count') ax1.set_xlabel('风险评分') # 添加5%和95%分位数竖线 q5 = np.percentile(simulation_results, 5) q95 = np.percentile(simulation_results, 95) ax1.axvline(q5, color='green', linestyle='--', label='5%分位数') ax1.axvline(q95, color='blue', linestyle='--', label='95%分位数') ax1.legend() # 绘制累积概率(Y轴2:0-1范围) ax2 = ax1.twinx() cumulative_prob = np.cumsum(counts) / total_samples ax2.plot(bins[:-1], cumulative_prob, color='red', linewidth=2) ax2.set_ylim(0, 1) # 关键:强制Y轴范围 ax2.set_ylabel('累积概率') plt.tight_layout() plt.show()
额外排查点
- 检查是否在计算累积概率时,误将bin的数量当成了总样本数(比如用
len(bins)代替len(simulation_results)) - 确认模拟结果的样本数量是否正确,避免因样本数统计错误导致归一化偏差
内容的提问来源于stack exchange,提问作者Paul Hanson
相关产品推荐
相关产品推荐

