VectorBT热力图:Series值显示错误与DataFrame标签优化问题
VectorBT热力图:Series与DataFrame行为差异及修复方案
一、Series与DataFrame生成热力图的行为差异原因
VectorBT对两种数据结构的热力图处理逻辑存在本质区别:
- 带MultiIndex的Series:默认将索引层级视为连续数值维度,会自动进行插值或网格化处理,而非直接映射为离散类别。这会导致额外生成不存在的数据点,破坏原始数据对应关系。
- DataFrame:直接将行/列作为离散类别映射到热力图轴,每个单元格严格对应DataFrame的具体值,无额外插值操作,因此值显示准确。
二、Series热力图值错误的根源
你的Series中rel_mom_entry层级全为单一值0,rel_mom_exit为多个离散数值。VectorBT默认将两个层级都当作连续数值轴处理:
- 因
rel_mom_entry只有0,会自动扩展出极小的x轴区间; - 对
rel_mom_exit的数值进行网格化插值,生成大量非原始数据点; - 即使添加
is_x_category=True/is_y_category=True,MultiIndex的结构仍会导致内部值映射逻辑混乱,无法将每个元组对应到唯一热力图单元格。
三、修复方案
方案1:修复Series热力图
强制VectorBT将索引层级作为离散类别处理,禁用插值,确保仅渲染真实数据点:
# 提取索引层级的唯一类别值 x_cats = new_series.index.get_level_values('rel_mom_entry').unique() y_cats = new_series.index.get_level_values('rel_mom_exit').unique() # 生成热力图并配置关键参数 fig = new_series.vbt.heatmap( x_level='rel_mom_entry', y_level='rel_mom_exit', is_x_category=True, is_y_category=True, x_categories=x_cats, y_categories=y_cats, interpolation='none' # 禁用插值,只显示原始数据 ) fig.show()
方案2:优化DataFrame热力图标签
先将Series转为DataFrame,再通过自定义布局优化标签显示:
# 将Series转换为DataFrame(按rel_mom_entry拆列为列) df = new_series.unstack(level='rel_mom_entry') # 生成基础热力图 fig = df.vbt.heatmap() # 自定义轴标签与刻度 fig.update_layout( xaxis_title='rel_mom_entry', yaxis_title='rel_mom_exit', xaxis=dict(tickmode='array', tickvals=[0], ticktext=['0']), yaxis=dict(tickmode='array', tickvals=y_cats, ticktext=[str(val) for val in y_cats]) ) # 自定义悬停文本(可选,提升可读性) fig.update_traces( hovertemplate='rel_mom_entry: %{x}<br>rel_mom_exit: %{y}<br>值: %{z}<extra></extra>' ) fig.show()
内容的提问来源于stack exchange,提问作者bend_it_like_backend
相关产品推荐
相关产品推荐

