Gridspec里面的Gridspec

时间:2017-11-07 07:36:51

标签: python matplotlib

我想在Gridpec中创建一个GridSpec。 我可以在这里创建一些像我的代码一样的GridSpec:

import matplotlib.pyplot as plt

for i in range(40):
    i = i + 1
    ax1 = plt.subplot(10, 4, i)
    plt.axis('on')
    ax1.set_xticklabels([])
    ax1.set_yticklabels([])
    ax1.set_aspect('equal')
    plt.subplots_adjust(wspace=None, hspace=None)
plt.show()

但我想要40格。 在每个Gridspec应该是另外21个网格(inner_grid) 并且在每个inner_grid中应该是顶部的一个网格,并且连续的6个网格应该填充其余部分。 几乎像这个链接末尾的图片: https://matplotlib.org/tutorials/intermediate/gridspec.html 但我真的不明白。

我试过这个:

import matplotlib as mpl
from matplotlib.gridspec import GridSpec
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(5,10), dpi=300)
    ax = plt.subplot(gs[i])
    #trying to make multiple gridspec
    # gridspec inside gridspec
        outer_grid = gridspec.GridSpec(48, 1, wspace=0.0, hspace=0.0)

        for i in range(21):
            #ax = plt.subplot(5, 5, i)
            inner_grid = gridspec.GridSpecFromSubplotSpec(5, 5, subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0)
            a, b = int(i/4)+1, i % 4+1
            for j in enumerate(product(range(1, 4), repeat=2)):
                ax = plt.Subplot(fig, inner_grid[j])
                ax.set_xticks([])
                ax.set_yticks([])
                fig.add_subplot(ax)

    all_axes = fig.get_axes()

1 个答案:

答案 0 :(得分:0)

你确定你想做什么?一个图中的40 * 21 * 6 = 5040轴...... 此外,您的描述(每个单元格中包含40个单元格和21个内部单元格的网格)与您提供的48个单元格中提供的代码不匹配,每个单元格中包含25个单元格...

无论如何,这就是我如何生成你所描述的内容。请注意,您不必生成中间Axes对象。只生成要绘制内容的轴。

最后,根据您实际想要实现的目标,我非常确定必须有一种比创建数千个轴更好的方法。

import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(40,100))


outer_grid = gridspec.GridSpec(10,4, wspace=0, hspace=0)

for outer in outer_grid:
    # ax = fig.add_subplot(outer)
    # ax.set_xticklabels([])
    # ax.set_yticklabels([])
    # ax.set_aspect('equal')

    inner_grid_1 = gridspec.GridSpecFromSubplotSpec(5,5, subplot_spec=outer)
    for inner in inner_grid_1:
        # ax1 = fig.add_subplot(inner)
        # ax1.set_xticklabels([])
        # ax1.set_yticklabels([])
        # ax1.set_aspect('equal')

        inner_grid_2 = gridspec.GridSpecFromSubplotSpec(2,6, subplot_spec=inner)
        ax_top = fig.add_subplot(inner_grid_2[0,:]) # top row
        for i in range(6):
            ax2 = fig.add_subplot(inner_grid_2[1,i]) # bottom row
            ax2.set_xticklabels([])
            ax2.set_yticklabels([])

plt.show()