我有一个我想使用的绘图布局,其中 9 个不同的数据簇被布置在一个方形网格上。网格中的每个框都包含 3 个并排布置的箱线图。
我最初的想法是这将适合 3x3 子图布局,每个单独的子图本身被划分为 3x1 子图布局。
我已经看到了:在 matplotlib中的子图中嵌入小图,这似乎可以让您在子图中定义单独的、手动放置的图。然而,将子图空间递归分割成 < 10 个易于寻址的子图的网格的想法似乎是一个显而易见的想法,我不敢相信它没有被直接实现。
我认为这里的嵌套 gridspec 示例正是您要寻找的。
我已经将他们的示例改编为您描述的网格模式的模型,它使用 gridspec 创建一个轴列表,然后迭代它们的索引以填充它们。这种方法应该符合您对“3x3 子图布局,每个单独的子图本身被划分为 3x1 子图布局”的需求。
import matplotlib as mpl
from matplotlib import gridspec
from matplotlib import pyplot as plt
f= plt.figure(figsize=(5, 5))
gs = gridspec.GridSpec(3, 3, wspace=0.5, hspace=0.2) #these are the 9 clusters
for i in range(9):
nested_gs = gridspec.GridSpecFromSubplotSpec(1, 3, subplot_spec=gs[i], wspace=0.5) # 1 row, 3 columns for each cluster
for j in range(3): #these are the 3 side by side boxplots within each cluster
ax = plt.Subplot(f, nested_gs[j])
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center", fontsize=9)
#ax.boxplot(data) # this is where you'd add your boxplots to the axes
# the following just cleans up each axes for readability
for tl in ax.get_xticklabels():
tl.set_visible(False)
for tl in ax.get_yticklabels():
tl.set_visible(False)
if ax.is_first_col():
tl.set_visible(True)
tl.set_fontsize(9)
f.add_subplot(ax)
f.savefig('nested_subplot.png')
Run Code Online (Sandbox Code Playgroud)
我希望这有助于您入门。
编辑以包括图像: