删除 matplotlib 子图中的多余图

Remove the extra plot in the matplotlib subplot

我想在 2 x 3 设置中绘制 5 个数据框(即 2 行和 3 列)。这是我的代码:但是在第 6 个位置(第二行和第三列)有一个额外的空图,我想去掉它。我想知道如何删除它,以便第一行有三个地块,第二行有两个地块。

import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=3)

fig.set_figheight(8)
fig.set_figwidth(15)



df[2].plot(kind='bar',ax=axes[0,0]); axes[0,0].set_title('2')

df[4].plot(kind='bar',ax=axes[0,1]); axes[0,1].set_title('4')

df[6].plot(kind='bar',ax=axes[0,2]); axes[0,2].set_title('6')

df[8].plot(kind='bar',ax=axes[1,0]); axes[1,0].set_title('8')

df[10].plot(kind='bar',ax=axes[1,1]); axes[1,1].set_title('10')

plt.setp(axes, xticks=np.arange(len(observations)), xticklabels=map(str,observations),
        yticks=[0,1])

fig.tight_layout()

试试这个:

fig.delaxes(axes[1][2])

创建子图的更灵活的方法是 fig.add_axes() 方法。参数是一个矩形坐标列表:fig.add_axes([x, y, xsize, ysize])。这些值是相对于 canvas 大小的,因此 0.5xsize 表示子图的宽度是 window.

的一半

或者,使用 axes 方法 set_axis_off():

axes[1,2].set_axis_off()

如果你知道要删除哪个地块,你可以给出索引并像这样删除:

axes.flat[-1].set_visible(False) # to remove last plot

关闭所有轴,只有在绘制时才一个一个地打开它们。那么你不需要提前知道索引,例如:

import matplotlib.pyplot as plt

columns = ["a", "b", "c", "d"]
fig, axes = plt.subplots(nrows=len(columns))

for ax in axes:
    ax.set_axis_off()

for c, ax in zip(columns, axes):
    if c == "d":
        print("I didn't actually need 'd'")
        continue

    ax.set_axis_on()
    ax.set_title(c)

plt.tight_layout()
plt.show()

以前的解决方案不适用于 sharex=True。如果你有,请考虑下面的解决方案,它也处理二维子图布局。

import matplotlib.pyplot as plt


columns = ["a", "b", "c", "d"]
fig, axes = plt.subplots(4,1, sharex=True)


plotted = {}
for c, ax in zip(columns, axes.ravel()):
    plotted[ax] = 0
    if c == "d":
        print("I didn't actually need 'd'")
        continue
    ax.plot([1,2,3,4,5,6,5,4,6,7])
    ax.set_title(c)
    plotted[ax] = 1

if axes.ndim == 2:
    for a, axs in enumerate(reversed(axes)):
        for b, ax in enumerate(reversed(axs)):
            if plotted[ax] == 0:
                # one can use get_lines(), get_images(), findobj() for the propose
                ax.set_axis_off()
                # now find the plot above
                axes[-2-a][-1-b].xaxis.set_tick_params(which='both', labelbottom=True)
            else:
                break # usually only the last few plots are empty, but delete this line if not the case
else:
    for i, ax in enumerate(reversed(axes)):
        if plotted[ax] == 0:
            ax.set_axis_off()
            axes[-2-i].xaxis.set_tick_params(which='both', labelbottom=True)
            # should also work with horizontal subplots
            # all modifications to the tick params should happen after this
        else:
            break

plt.show()

二维fig, axes = plot.subplots(2,2, sharex=True)