基于经验数据绘制x轴为累计值的阶跃函数实现咨询
代码修改方案
你当前的代码缺失了Demand列按WTP排序后的累计求和步骤,因此无法得到x轴递增的类ECDF阶跃效果,按以下逻辑调整即可:
- 对WTP升序排序后的数据集,新增累计Demand列作为x轴数据源
- 调整
plt.step的where参数为post,匹配阶跃上升的逻辑:累计Demand达到当前阈值后,WTP才跳升到下一个取值
修改后的完整代码如下:
import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns Demand_quantity = pd.Series([13, 443.9, 419.6, 295.9, 150.2]) Demand_WTP = [111.3, 152.9, 98.2, 625.5, 210.4] demand_data = {'Demand':Demand_quantity, 'WTP':Demand_WTP} Demand = pd.DataFrame(demand_data) # 按WTP升序排序 Demand.sort_values(by = 'WTP', axis = 0, inplace = True) # 新增累计Demand列作为x轴 Demand['cum_Demand'] = Demand['Demand'].cumsum() print(Demand) # 绘制阶跃曲线,where设为post匹配需求逻辑 plt.step(Demand['cum_Demand'], Demand['WTP'], where='post', label='WTP阶跃曲线') # 可选:添加坐标轴标注 plt.xlabel('累计Demand') plt.ylabel('WTP实际值') plt.legend(title='曲线类型') plt.title('WTP随累计Demand变化阶跃图') plt.show()
如果需要曲线从x=0的位置开始绘制,可以手动在数据开头插入原点:
# 在排序后插入起始点 Demand = pd.concat([pd.DataFrame({'Demand':[0], 'WTP':[Demand['WTP'].iloc[0]], 'cum_Demand':[0]}), Demand], ignore_index=True)
内容的提问来源于stack exchange,提问作者JeppeBay
相关产品推荐
相关产品推荐

