删除matplotlib子图中的额外图

Him*_*nAB 7 python matplotlib subplot

我想在2乘3设置(即2行和3列)中绘制5个数据帧.这是我的代码:但是在第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()
Run Code Online (Sandbox Code Playgroud)

地块

Joh*_*nes 21

试试这个:

fig.delaxes(axes[1][2])
Run Code Online (Sandbox Code Playgroud)

创建子图的fig.add_axes()一种更灵活的方法是方法.参数是rect坐标列表:fig.add_axes([x,y,xsize,ysize]).这些值是相对于画布大小的,因此xsize为0.5表示子图的宽度是窗口宽度的一半.

  • 使用`add_axes`既不是一个非常好的也不是推荐的生成子图的方法.无论是`plt.subplots`还是`Gridspec`都是可行的方式,`delaxes`或`ax.axis("off")`可用于删除或隐藏子图. (2认同)

Jas*_*mar 9

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

axes.flat[-1].set_visible(False) # to remove last plot
Run Code Online (Sandbox Code Playgroud)


kom*_*an_ 9

关闭所有轴,仅当您在轴上绘图时才将它们一一打开。那么你不需要提前知道索引,例如:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • +1,因为当我编写一般绘图例程并且不知道会有多少子图时,它效果最好。所有其他答案对于OP的问题都是严格正确的,但这是更通用的。 (4认同)

Ket*_*tan 5

或者,使用axes方法set_axis_off()

axes[1,2].set_axis_off()
Run Code Online (Sandbox Code Playgroud)