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

《Python数据分析进阶》累积分布函数绘图代码报错求助

Python累积分布函数(CDF)绘图报错修复

错误原因分析

报错信息明确指出xvalues与yvalues维度不匹配:shapes (4,) and (503,),核心问题出在自定义plot_cdf函数的x值提取逻辑错误:

  • 原代码中xvalues = bin_edges[:1]仅提取了直方图区间边缘的第一个值,导致xvalues初始长度仅为1,后续拼接后总长度为4
  • 而yvalues是数据累计求和的结果,长度等于数据点数量加前后填充值,总长度为503,二者维度无法匹配

关键错误定位

plot_cdf函数中这一行是问题根源:

xvalues = bin_edges[:1]

np.histogram返回的bin_edges长度为counts长度+1,正确逻辑应取bin_edges[:-1](所有直方图左边缘),才能和counts的长度一一对应。

修复后的完整代码

导入模块

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.stats import weibull_min  # 补充原代码缺失的分布定义

修复后的CDF绘图函数

# 定义累积分布函数(CDF)绘图函数
def plot_cdf(data, plot_range=None, scale_to=None, **kwargs):
    sorted_data = np.array(sorted(data), dtype=np.float64)
    num_bins = len(data)
    counts, bin_edges = np.histogram(sorted_data, bins=num_bins)
    
    # 修复x值提取:取所有直方图左边缘,与counts长度匹配
    xvalues = bin_edges[:-1]
    yvalues = np.cumsum(counts)
    
    if plot_range is None:
        xmin = sorted_data[0]
        xmax = sorted_data[-1]
    else:
        xmin, xmax = plot_range
    
    # 填充数组,保证CDF曲线首尾对齐
    xvalues = np.concatenate([[xmin], xvalues, [xmax]])
    yvalues = np.concatenate([[0.0], yvalues, [yvalues.max()]])
    
    if scale_to is not None:
        yvalues = yvalues / len(data) * scale_to
    
    plt.axis([xmin, xmax, 0, yvalues.max()])
    return plt.plot(xvalues, yvalues, **kwargs)

调用示例(补充原代码缺失的样本生成)

# 生成Weibull分布样本(原代码缺失部分)
rvweib = weibull_min(c=1.5)
weib_variates = rvweib.rvs(size=500)

xmin = 0
xmax = 3.5
xx = np.linspace(xmin, xmax, 200)
plt.plot(xx, rvweib.cdf(xx), color='orange', lw=5)
plot_cdf(weib_variates, plot_range=[xmin, xmax], scale_to=1, lw=2, color='green')
plt.axis([xmin, xmax, 0, 1])
plt.title('Weibul distribution simulation', fontsize=14)
plt.xlabel('Failure Time', fontsize=12)
plt.show()

额外说明

  1. 补充了原代码缺失的scipy.stats.weibull_min导入和样本生成逻辑,确保代码可直接运行
  2. 移除调试用print语句,保持代码整洁
  3. 调整首尾填充逻辑,让CDF曲线从(xmin, 0)开始、(xmax, 1)结束,符合CDF数学定义

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 18:15:54