【问题标题】:Does the facility exist within matplotlib to define subplot grids within subplots?matplotlib 中是否存在用于在子图中定义子图网格的工具?
【发布时间】:2017-10-06 13:26:18
【问题描述】:

我有一个想要使用的绘图布局,其中 9 个不同的数据集群布置在方形网格上。网格中的每个框都包含 3 个并排放置的箱线图。

我最初的想法是这将适合 3x3 子图布局,每个单独的子图本身都被划分为 3x1 子图布局。

我见过这个:Embedding small plots inside subplots in matplotlib,它似乎可以让您在子图中定义单独的手动放置的图。然而,递归地将子图空间分割成小于 10 个易于寻址的子图的网格的想法似乎是一个显而易见的想法,我不敢相信它没有被直接实现。

【问题讨论】:

    标签: matplotlib


    【解决方案1】:

    Matplotlib 具有扁平的层次结构。您有一个数字,其中有一个未确定且未绑定的数字轴。因此不存在子图的子图。但当然,您可以放置​​轴,使它们看起来嵌入在其他子图中。

    不过,可以使用多层子图网格。 这在gridspec guide 中有详细说明。 你可能对GridSpecFromSubplotSpec 的使用特别感兴趣,它允许产生this example

    gs0 = gridspec.GridSpec(1, 2)
    
    gs00 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[0])
    gs01 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[1])
    

    【讨论】:

    • 谢谢欧内斯特,我会调查一下 - 一开始我不清楚代码如何在下面的轴布局中发布结果,但我会仔细看看,谢谢你的领导.
    【解决方案2】:

    我认为嵌套 gridspec 示例 here 是您正在寻找的。​​p>

    我已将他们的示例改编为您描述的网格模式的模型,该模型使用 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')
    

    我希望这可以帮助您入门。

    已编辑以包含图像:

    【讨论】:

      猜你喜欢
      • 2012-09-04
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 2018-01-11
      • 2011-05-18
      • 2020-09-23
      • 2021-03-23
      • 2014-02-03
      相关资源
      最近更新 更多