堆叠柱状图与前置折线图绘制问题:zorder与双坐标轴不兼容
解决堆叠柱状图覆盖折线图的问题
问题核心在于twinx()创建的副轴(ax2)默认图层优先级高于主轴(ax1)——哪怕你给柱状图设置了zorder=-1,由于轴本身处于上层,柱状图还是会盖住主轴的折线。
解决步骤
- 调整两个轴的图层顺序,让主轴(ax1)的
zorder高于副轴(ax2) - 将主轴背景设为透明,避免遮挡副轴的刻度与内容
修改后的关键代码片段
# 创建副轴后添加以下配置 ax2.set_zorder(0) ax1.set_zorder(1) ax1.patch.set_visible(False) # 隐藏主轴背景,防止覆盖副轴元素
完整修改代码
import matplotlib.pyplot as plt import pandas as pd import numpy as np # 示例数据 data = { 'month_year': ['Jan-2023', 'Feb-2023', 'Mar-2023', 'Apr-2023'], 'gas_share': [30, 25, 20, 35], 'lignite_share': [50, 40, 45, 30], 'coal_share': [20, 35, 35, 35], 'final_residual': [500, 600, 550, 650] } df = pd.DataFrame(data) # 创建画布与主轴 fig, ax1 = plt.subplots(figsize=(10, 6)) # 创建右侧副轴 ax2 = ax1.twinx() # 调整轴的图层顺序与背景透明度 ax2.set_zorder(0) ax1.set_zorder(1) ax1.patch.set_visible(False) # 绘制堆叠柱状图 width = 0.4 bar1 = np.arange(len(df['month_year'])) ax2.bar(bar1, df['gas_share'], width, label='Gas Share', color='#FF9999') ax2.bar(bar1, df['lignite_share'], width, bottom=df['gas_share'], label='Lignite Share', color='#66B2FF') ax2.bar(bar1, df['coal_share'], width, bottom=df['gas_share'] + df['lignite_share'], label='Coal Share', color='#99FF99') # 配置副轴标签与刻度 ax2.set_ylabel('Share (%)') ax2.set_xticks(bar1) ax2.set_xticklabels(df['month_year']) ax2.tick_params(axis='y') # 绘制折线图(现在会显示在柱状图上方) ax1.plot(df['month_year'], df['final_residual'], color='black', label='Final Residual', marker='o', linewidth=2) ax1.set_xlabel('Month-Year') ax1.set_ylabel('Final Residual') ax1.tick_params(axis='y') # 添加网格 ax1.grid(True) # 添加图例并调整位置 fig.legend(loc="upper center", bbox_to_anchor=(0.5, -0.05), ncol=4) # 美化与展示 plt.title("Final Residual and Share % Over Time") plt.xticks(rotation=45) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者tereos_jon_doe
相关产品推荐
相关产品推荐

