如何用Matplotlib组合图替换分面布局中的最后一个柱状图?
解决Matplotlib 2×2分面布局中替换子图为组合图的问题
你遇到的问题核心是:组合图代码里重新创建了新的figure和axes,没有复用2×2布局里已有的axs[1,1]。直接把现有子图轴替换进去就行,不需要重新生成新的画布。
以下是修正后的完整代码:
import pandas as pd import matplotlib.pyplot as plt from matplotlib.cm import get_cmap # 创建2×2分面布局 fig, axs = plt.subplots(2,2, figsize=(17,10)) plt.subplots_adjust(wspace=0.2, hspace=0.3) # 绘制前三个堆叠柱状图 df.plot(x='year', kind='bar', stacked=True, title='Title 1', ax=axs[0,0], legend=True) df.plot(x='year', kind='bar', stacked=True, title='Title 2', ax=axs[0,1], legend=None) df.plot(x='year', kind='bar', stacked=True, title='Title 3', ax=axs[1,0], legend=True) # 替换最后一个子图为柱状+折线组合图 ax_1 = axs[1,1] # 直接使用已有的子图轴 ax_2 = ax_1.twinx() cmap = get_cmap('tab10') ax_1.bar(df['year'], df['open'], label='open', color=cmap(0)) ax_2.plot(df['year'], df['closed'], label='closed', color=cmap(0.1), linewidth=4.5) # 合并两个轴的图例 handles_1, labels_1 = ax_1.get_legend_handles_labels() handles_2, labels_2 = ax_2.get_legend_handles_labels() ax_1.legend(handles=handles_1 + handles_2, labels=labels_1 + labels_2, loc='upper left', shadow=True) # 设置子图样式和标题 ax_1.grid(axis='y') ax_1.set_title('Sales comparison') # 设置总标题 plt.suptitle('Description of...', fontsize=16) plt.show()
关键修改说明:
- 删掉组合图代码里的
fig, ax_1 = plt.subplots(figsize=(8,5)),直接用ax_1 = axs[1,1]复用已有的子图轴 - 保留原组合图的绘图、图例合并、样式设置逻辑,全部适配到
ax_1上 - 不需要单独调用
plt.show()在组合图里,最后统一调用一次即可
这样就能完美把最后一个子图替换成你需要的组合图,同时保持整个2×2布局的一致性。
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

