如何在Matplotlib子图内嵌套子图?
在Matplotlib子图中嵌套子图的实现方案
问题描述
需要将主Figure中位置为223的单个子图,替换为包含上下两个子图的嵌套结构,已编写嵌套子图代码,但不清楚绘图对象层级关系,无法完成嵌入。
现有主绘图代码
import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl from pandas import util import pandas.util.testing as testing import pandas as pd df = util.testing.makeDataFrame() with mpl.rc_context(rc={'font.family': 'serif', 'font.weight': 'light', 'font.size': 12}): fig = plt.figure(figsize= (12, 6), dpi =200) ax = fig.add_subplot(2, 2, (1,2)) ax2 = ax.twinx() df['A'].plot(ax=ax, color = 'g') df['B'].plot(ax=ax2, color ='g') fig.add_subplot(223) df['C'].plot(color='r') plt.axvline(x = 7, color = 'b', label = 'axvline - full height') fig.add_subplot(2,2,4) df = df.round(0) ax3 = df['D'].plot(kind='bar') ax3.legend( prop={'size': 6}) fig.tight_layout() plt.show()
目标嵌套子图代码
fig = plt.figure(dpi =200) fig.subplots_adjust(hspace= 0) ax5 = fig.add_subplot(3,1,(1,2)) df['A'].plot(color='r') plt.axvline(x = 7, color = 'b', label = 'axvline - full height') ax6 = fig.add_subplot(3,1,(3) , sharex = ax5) df['A'].plot(color='r')
实现方案
核心是利用matplotlib.gridspec.GridSpec灵活拆分目标子图区域,创建嵌套的子网格布局,以下是修改后的完整可运行代码:
修改后的完整代码
import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl from pandas import util import pandas.util.testing as testing import pandas as pd from matplotlib.gridspec import GridSpec df = util.testing.makeDataFrame() with mpl.rc_context(rc={'font.family': 'serif', 'font.weight': 'light', 'font.size': 12}): fig = plt.figure(figsize=(12, 6), dpi=200) # 定义主布局的2行2列网格 main_gs = GridSpec(2, 2, figure=fig) # 顶部跨列子图(原代码中的2,2,(1,2)) ax = fig.add_subplot(main_gs[0, :]) ax2 = ax.twinx() df['A'].plot(ax=ax, color='g') df['B'].plot(ax=ax2, color='g') # 将原223的位置拆分为2行1列的嵌套网格 nested_gs = main_gs[1, 0].subgridspec(2, 1, hspace=0) # 嵌套子图1(上层) ax5 = fig.add_subplot(nested_gs[0]) df['A'].plot(color='r', ax=ax5) ax5.axvline(x=7, color='b', label='axvline - full height') ax5.legend() # 嵌套子图2(下层),共享x轴 ax6 = fig.add_subplot(nested_gs[1], sharex=ax5) df['A'].plot(color='r', ax=ax6) # 隐藏上层子图的x轴刻度,避免重复显示 plt.setp(ax5.get_xticklabels(), visible=False) # 右下角的柱状图子图(原代码中的2,2,4) ax3 = fig.add_subplot(main_gs[1, 1]) df_round = df.round(0) df_round['D'].plot(kind='bar', ax=ax3) ax3.legend(prop={'size': 6}) fig.tight_layout() plt.show()
关键细节说明
- 主网格布局:用
GridSpec替代传统的add_subplot(2,2,...),可以更精准地控制每个子图区域的拆分与组合。 - 嵌套网格创建:通过
main_gs[1,0].subgridspec(2,1),把主布局中第2行第1列的区域拆分为2行1列的子网格,实现嵌套子图的放置。 - 轴共享优化:设置
sharex=ax5让两个嵌套子图共享x轴,同时隐藏上层子图的x刻度,避免视觉冗余。 - 间距控制:
hspace=0参数消除嵌套子图之间的垂直间距,实现紧密排列效果。
内容的提问来源于stack exchange,提问作者Slartibartfast
相关产品推荐
相关产品推荐

