如何用matplotlib将两个带趋势线的双Y轴柱状图并排展示
双图左右并排展示的修改方案
问题核心原因
- 原代码两次独立调用
plt.subplots()生成了两个完全独立的画布,天然为上下堆叠关系 - 此前尝试调整子图布局失败,多是因为未将pandas绘图函数的目标坐标轴绑定到预先创建的子图网格,导致绘图逻辑脱离了统一的画布布局
此前调整失败的常见原因
- 未向pandas的
plot()方法传入ax参数指定目标坐标轴,pandas默认会为每次绘图创建独立的坐标轴和画布,和预先创建的子图网格完全脱节 - 两次调用
plt.subplots()分别创建独立画布,不同画布的内容无法在同一展示窗口内并排排布 - 双Y轴
twinx()生成的新坐标轴没有绑定到对应子图,导致趋势线偏移到其他画布的位置
修改后可直接运行的代码
import matplotlib.pyplot as plt import numpy as np # 按原有业务逻辑定义截取的特征数量 # HOW_MANY = 15 # 创建1行2列的单画布子图网格,适配并排展示的尺寸 fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(16, 7)) # ---------- 左侧子图:频率与累计占比 ---------- # 左轴:失败频率柱状图 df.iloc[:HOW_MANY,:]['FailCount'].plot( kind="bar", stacked=True, legend=False, ax=ax_left, color='green', title="Frequency of failure vs Feature (Cumulative %)" ) ax_left.set_ylabel('Frequency', color='b') ax_left.tick_params('y', colors='b') ax_left.set_xticklabels(np.asarray(df['Feature'])[:HOW_MANY]) # 右轴:累计占比趋势线 ax_left_twin = ax_left.twinx() ax_left_twin.plot( np.asarray(df['Cummulative_aggr'])[:HOW_MANY], linestyle='--', marker='s', color='r', label='cummulative %' ) ax_left_twin.set_ylabel('Cummulative %', color='r') # 合并双轴的图例 h1, l1 = ax_left.get_legend_handles_labels() h1t, l1t = ax_left_twin.get_legend_handles_labels() ax_left.legend(h1 + h1t, l1 + l1t, loc='best') # ---------- 右侧子图:频率与良率损失 ---------- # 左轴:失败频率柱状图 df.iloc[:HOW_MANY,:]['FailCount'].plot( kind="bar", stacked=True, legend=False, ax=ax_right, color='green', title="Frequency of failure vs Feature (Yield Loss)" ) ax_right.set_ylabel('Frequency', color='b') ax_right.tick_params('y', colors='b') ax_right.set_xticklabels(np.asarray(df['Feature'])[:HOW_MANY]) # 右轴:良率损失趋势线 ax_right_twin = ax_right.twinx() ax_right_twin.plot( np.asarray(df['Yield_Loss'])[:HOW_MANY], linestyle='--', marker='s', color='black', label='Yield Loss' ) ax_right_twin.set_ylabel('Yield Loss', color='black') # 合并双轴的图例 h2, l2 = ax_right.get_legend_handles_labels() h2t, l2t = ax_right_twin.get_legend_handles_labels() ax_right.legend(h2 + h2t, l2 + l2t, loc='best') plt.tight_layout() plt.show()
关键修改点说明
- 所有绘图逻辑都绑定到同一个单画布的两个子图坐标轴上,不再单独创建独立画布
- pandas的
bar绘图通过ax参数指定目标坐标轴,避免自动生成新画布 - 双Y轴的
twinx()直接绑定到对应子图的坐标轴,保证趋势线和柱状图在同一子图内对齐 - 自动合并每个子图内双轴的图例,解决原来双轴图例分散的问题
内容的提问来源于stack exchange,提问作者Kartik Mehra
相关产品推荐
相关产品推荐

