关于python:如何在matplotlib中制作空白子图?

How can I make a blank subplot in matplotlib?

我在matplotlib中制作了一组子图(例如3 x 2),但我的数据集少于6个。 如何将其余子图留空?

安排如下所示:

1
2
3
4
5
6
7
+----+----+
| 0,0| 0,1|
+----+----+
| 1,0| 1,1|
+----+----+
| 2,0| 2,1|
+----+----+

这可能会持续几页,但是在最后一页上,例如,有5个数据集,而2,1框将为空。 但是,我声明该数字为:

1
cfig,ax = plt.subplots(3,2)

因此,在子图2,1的空间中,存在一组带有刻度和标签的默认轴。 如何以编程方式使该空间空白且没有轴?


您始终可以隐藏不需要的轴。 例如,以下代码完全旋转第6轴:

1
2
3
4
5
6
import matplotlib.pyplot as plt

hf, ha = plt.subplots(3,2)
ha[-1, -1].axis('off')

plt.show()

结果如下图:

enter image description here

或者,请参阅对问题的可接受答案,将其隐藏在matplotlib图中,以保留轴但隐藏所有轴装饰(例如刻度线和标签)。


自从首次提出此问题以来,已向matplotlib添加了经过改进的子图接口。 在这里,您可以准确地创建所需的子图,而不会隐藏其他内容。 此外,子图可以跨越其他行或列。

1
2
3
4
5
6
7
8
9
import pylab as plt

ax1 = plt.subplot2grid((3,2),(0, 0))
ax2 = plt.subplot2grid((3,2),(0, 1))
ax3 = plt.subplot2grid((3,2),(1, 0))
ax4 = plt.subplot2grid((3,2),(1, 1))
ax5 = plt.subplot2grid((3,2),(2, 0))

plt.show()

enter image description here


也可以使用Axes.set_visible()方法隐藏子图。

1
2
3
4
5
6
7
8
9
10
11
import matplotlib.pyplot as plt
import pandas as pd

fig = plt.figure()
data = pd.read_csv('sampledata.csv')

for i in range(0,6):
ax = fig.add_subplot(3,2,i+1)
ax.plot(range(1,6), data[i])
if i == 5:
    ax.set_visible(False)


在需要时可以选择创建子图吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib
matplotlib.use("pdf")
import matplotlib.pyplot as plt

plt.figure()
plt.gcf().add_subplot(421)
plt.fill([0,0,1,1],[0,1,1,0])
plt.gcf().add_subplot(422)
plt.fill([0,0,1,1],[0,1,1,0])
plt.gcf().add_subplot(423)
plt.fill([0,0,1,1],[0,1,1,0])
plt.suptitle("Figure Title")
plt.gcf().subplots_adjust(hspace=0.5,wspace=0.5)
plt.savefig("outfig")