如何用Matplotlib绘制基于Pandas DataFrame的双值蜡烛状柱状图
双值蜡烛状图表实现方案
用Matplotlib原生实现
步骤1:准备数据
先创建示例DataFrame(替换成你的实际数据即可):
import pandas as pd import matplotlib.pyplot as plt # 示例数据 data = { 'Title': ['A', 'B', 'C', 'D'], 'Value_A': [0.1, 0.5, 0.2, 0.7], 'Value_B': [0.3, 0.6, 0.4, 0.9] } df = pd.DataFrame(data)
步骤2:绘制蜡烛状竖线+标记点
这种方式直接展示每个类别下两个值的范围,用竖线连接,两端用不同颜色标记:
plt.figure(figsize=(8, 5)) # 设置x轴位置(对应每个Title) x_pos = range(len(df)) # 绘制连接Value_A和Value_B的竖线 for idx in x_pos: plt.plot([idx, idx], [df['Value_A'][idx], df['Value_B'][idx]], color='black', linewidth=2) # 标记两个值的点 plt.scatter(x_pos, df['Value_A'], color='#1f77b4', s=60, label='Value_A') plt.scatter(x_pos, df['Value_B'], color='#ff7f0e', s=60, label='Value_B') # 配置图表属性 plt.xticks(x_pos, df['Title']) plt.xlabel('类别') plt.ylabel('数值') plt.title('双值蜡烛状图表') plt.legend() plt.tight_layout() plt.show()
简化版:用errorbar快速实现
如果觉得循环画竖线麻烦,可以用errorbar函数自动生成范围线:
plt.figure(figsize=(8, 5)) x_pos = range(len(df)) # 计算中间值和上下误差 mid_values = (df['Value_A'] + df['Value_B']) / 2 error = (df['Value_B'] - df['Value_A']) / 2 plt.errorbar(x_pos, mid_values, yerr=[error, error], fmt='o', color='black', capsize=5, label='数值范围') plt.scatter(x_pos, df['Value_A'], color='#1f77b4', s=60, label='Value_A') plt.scatter(x_pos, df['Value_B'], color='#ff7f0e', s=60, label='Value_B') plt.xticks(x_pos, df['Title']) plt.xlabel('类别') plt.ylabel('数值') plt.title('双值蜡烛状图表') plt.legend() plt.tight_layout() plt.show()
用Plotly实现(交互版)
如果想要交互式图表,Plotly代码更简洁,还支持鼠标悬停查看数值:
import plotly.graph_objects as go fig = go.Figure() # 添加Value_A的标记点 fig.add_trace(go.Scatter( x=df['Title'], y=df['Value_A'], mode='markers', marker=dict(color='#1f77b4', size=10), name='Value_A' )) # 添加Value_B的标记点+连接竖线 fig.add_trace(go.Scatter( x=df['Title'], y=df['Value_B'], mode='markers+lines', line=dict(color='black', width=2), marker=dict(color='#ff7f0e', size=10), name='Value_B' )) # 配置布局 fig.update_layout( title='双值蜡烛状图表', xaxis_title='类别', yaxis_title='数值', showlegend=True ) fig.show()
内容的提问来源于stack exchange,提问作者Max Bushbeat
相关产品推荐
相关产品推荐

