如何用Matplotlib/Seaborn绘制带垂直线的分类散点资产价格图
用Matplotlib绘制资产价格极值与区间图表
解决方案代码
import pandas as pd import matplotlib.pyplot as plt import numpy as np # 初始化数据 df = pd.DataFrame({'A': [3.5,2,1.5], 'B': [3.5,1.7,1.7],'C': [3.5,0.7,0.7],'D': [3.5,1.1,1.1]}) # 设置x轴参数:资产名称与对应位置 assets = df.columns x_pos = np.arange(len(assets)) # 创建画布与坐标轴 fig, ax = plt.subplots(figsize=(8, 6)) # 遍历每个资产绘制元素 for idx, asset in enumerate(assets): current_high = df.iloc[0, idx] # 当前最高价 range_high = df.iloc[1, idx] # 指定时段价格上限 history_low = df.iloc[2, idx] # 历史最低价(同时为时段价格下限) # 绘制当前最高价实心点 ax.scatter(x_pos[idx], current_high, color='black', s=60, zorder=5) # 绘制历史最低价空心点 ax.scatter(x_pos[idx], history_low, color='black', s=60, facecolors='none', zorder=5) # 绘制时段价格上限空心点(若与下限不同则绘制) if range_high != history_low: ax.scatter(x_pos[idx], range_high, color='black', s=60, facecolors='none', zorder=5) # 绘制时段区间的水平短线 ax.hlines(y=[range_high, history_low], xmin=x_pos[idx]-0.15, xmax=x_pos[idx]+0.15, color='black') # 绘制连接当前最高价与历史最低价的垂直虚线 ax.vlines(x=x_pos[idx], ymin=history_low, ymax=current_high, linestyle='--', color='black') # 配置坐标轴与图表样式 ax.set_xticks(x_pos) ax.set_xticklabels(assets) ax.set_ylabel('价格') ax.set_title('资产价格极值与时段区间') ax.set_ylim(0, 4) ax.grid(axis='y', linestyle='-', alpha=0.6) # 优化布局并显示图表 plt.tight_layout() plt.show()
代码说明
数据映射:
df.iloc[0, idx]:对应当前最高价,用实心黑点标记df.iloc[2, idx]:对应历史最低价,用空心黑点标记df.iloc[1, idx]:对应指定时段的价格上限,若与历史最低价(时段下限)不同,同样用空心黑点标记,并添加水平短线明确区间范围
图表元素:
- 垂直虚线:连接当前最高价与历史最低价,展示价格极值跨度
- 水平短线:仅当时段区间上下限不同时绘制,清晰区分时段价格范围
- 分层绘制(
zorder=5):确保点在虚线和网格上方显示,避免被遮挡
样式调整:
- 设置y轴范围为
0-4,完整展示所有价格点 - 添加y轴网格线,提升价格读数的便利性
- 用
tight_layout()自动调整元素间距,避免标签重叠
- 设置y轴范围为
内容的提问来源于stack exchange,提问作者Sam333
相关产品推荐
相关产品推荐

