登录
首页 >  文章 >  python教程

Matplotlib双分布图合并与多线参考线添加教程

时间:2026-03-30 08:00:25 444浏览 收藏

本文手把手教你如何在Matplotlib与Seaborn协作下,精准合并看涨(CALL)与看跌(PUT)期权的CDF柱状图,并在统一、有序的执行价(Strike)x轴上正确添加多条关键百分位垂直参考线(如40%、80%),彻底规避因混淆原始行索引与绘图位置索引而导致的线条错位陷阱——不仅提供开箱即用的完整代码和关键注释,更提炼出“分位值→实际Strike→全局位置索引”的可靠映射范式,助你轻松复用于各类离散x轴上的统计标注场景。

Matplotlib 中合并双分布图并精准添加多条垂直参考线的完整教程

本文详解如何在 Matplotlib(配合 Seaborn)中合并 CALL 与 PUT 的 CDF 柱状图,并基于实际 Strike 值,在统一 x 轴上精准绘制多条百分位垂直线(如 40%、80%),避免因索引错位导致的线条偏移问题。

本文详解如何在 Matplotlib(配合 Seaborn)中合并 CALL 与 PUT 的 CDF 柱状图,并基于实际 Strike 值,在统一 x 轴上精准绘制多条百分位垂直线(如 40%、80%),避免因索引错位导致的线条偏移问题。

在金融数据分析中,常需对比看涨(CALL)与看跌(PUT)期权的累积分布函数(CDF),尤其关注关键分位点(如 40%、80%)所对应的执行价(Strike)。一个常见误区是:直接使用原始 DataFrame 的 .idxmin() 返回的行索引(如 0, 5, 12)作为 plt.axvline(x=...) 的横坐标——这仅在 x 轴严格按原始索引顺序排列时才有效。而当使用 sns.barplot 合并两个数据集后,x 轴实际由 sorted(unique(STRIKE)) 决定,其位置索引(0-based position)与原始 DataFrame 行索引完全脱钩。若不显式映射,垂直线将严重错位。

✅ 正确做法是:先构建全局有序 Strike 列表 → 查找目标 Strike 在该列表中的位置索引 → 以该位置索引为 axvline 的 x 值

以下为可直接运行的完整实现方案(含关键注释与最佳实践):

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

# Step 1: 准备数据(假设 CALL 和 PUT 已含 'STRIKE', 'CDF', 'Percentile' 列)
# 注意:确保 'STRIKE' 列为数值类型(非字符串),便于排序与匹配
CALL = CALL.copy()
PUT = PUT.copy()
CALL['hue'] = 1  # 标记为 CALL
PUT['hue'] = 2    # 标记为 PUT

# Step 2: 合并数据并生成全局唯一、升序 Strike 序列
res = pd.concat([CALL, PUT], ignore_index=True)
unique_strikes = sorted(res['STRIKE'].unique())  # 关键!构建统一x轴基准

# Step 3: 分别定位 CALL/PUT 的 40% 与 80% 对应 Strike 值(使用原始 DataFrame 计算)
nearest_40_call = CALL.loc[(CALL['Percentile'] - 0.4).abs().idxmin(), 'STRIKE']
nearest_80_call = CALL.loc[(CALL['Percentile'] - 0.8).abs().idxmin(), 'STRIKE']
nearest_40_put  = PUT.loc[(PUT['Percentile'] - 0.4).abs().idxmin(), 'STRIKE']
nearest_80_put  = PUT.loc[(PUT['Percentile'] - 0.8).abs().idxmin(), 'STRIKE']

# Step 4: 将每个目标 Strike 映射到全局 unique_strikes 中的位置索引
def strike_to_position(strike_val, strike_list):
    try:
        return strike_list.index(strike_val)  # 精确匹配(推荐:确保数据无精度误差)
    except ValueError:
        # 若存在浮点精度问题,改用近似匹配(可选)
        idx = np.argmin(np.abs(np.array(strike_list) - strike_val))
        return idx

ind_40c = strike_to_position(nearest_40_call, unique_strikes)
ind_80c = strike_to_position(nearest_80_call, unique_strikes)
ind_40p = strike_to_position(nearest_40_put,  unique_strikes)
ind_80p = strike_to_position(nearest_80_put,  unique_strikes)

# Step 5: 绘制合并柱状图 + 垂直线 + 标签
plt.figure(figsize=(16, 6))
ax = sns.barplot(data=res, x='STRIKE', y='CDF', hue='hue',
                 palette={1: 'lightgreen', 2: 'orange'}, dodge=True)

plt.xlabel('Strike Price')
plt.ylabel('Cumulative Distribution Function (CDF)')
plt.title('CDF Comparison: CALL vs PUT with Key Percentile Lines')
plt.xticks(rotation=60)

# 添加四条垂直线(统一风格,区分颜色可选)
for x_pos, label, color in [
    (ind_40c, f'40% CALL\n({nearest_40_call})', 'red'),
    (ind_80c, f'80% CALL\n({nearest_80_call})', 'darkred'),
    (ind_40p, f'40% PUT\n({nearest_40_put})', 'blue'),
    (ind_80p, f'80% PUT\n({nearest_80_put})', 'darkblue')
]:
    plt.axvline(x=x_pos, color=color, linestyle='--', linewidth=1.2, alpha=0.9)
    # 在顶部添加文本标签,提高可读性
    max_cdf = res['CDF'].max()
    plt.text(x_pos, max_cdf * 1.02, label, 
             ha='center', va='bottom', fontsize=9, color=color, fontweight='bold')

# 自定义图例(去除 seaborn 自动生成的 hue 图例,避免冗余)
handles = [plt.Rectangle((0,0),1,1, color='lightgreen', ec="k", lw=1.2),
           plt.Rectangle((0,0),1,1, color='orange', ec="k", lw=1.2)]
plt.legend(handles, ['CALL', 'PUT'], title='Option Type', loc='upper right')

plt.tight_layout()
plt.show()

⚠️ 关键注意事项

  • 数据类型一致性:确保 STRIKE 列为 float 或 int,避免字符串形式(如 '100.0')导致 list.index() 匹配失败;
  • 精度处理:若 Strike 为浮点数且存在微小计算误差,建议使用 np.argmin(np.abs(...)) 替代精确 index() 查找;
  • x 轴对齐原理:sns.barplot(x='STRIKE', ...) 默认将 STRIKE 值去重排序后作为 x 轴刻度,其内部位置索引即 range(len(unique_strikes)),因此必须将目标 Strike 映射至此索引空间;
  • 标签位置优化:plt.text() 的 y 坐标建议设为 max_cdf * 1.02 而非固定值,确保标签始终位于柱状图上方且自适应缩放;
  • 图例精简:禁用 seaborn 自动生成的 hue 图例,改用 Rectangle 手动构造,语义更清晰、样式更可控。

通过此方法,您不仅能准确叠加多组分布及其统计参考线,更能建立一套可复用的“分位线-位置映射”范式,适用于任何需在分类/离散 x 轴上标注关键数值点的场景。

理论要掌握,实操不能落!以上关于《Matplotlib双分布图合并与多线参考线添加教程》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>