如何在matplotlib中生成空白子块?

2024-05-14 00:19:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在matplotlib中创建了一组子块(比如3x 2),但是我只有不到6个数据集。我怎样才能使剩余的子批次为空?

安排如下:

+----+----+
| 0,0| 0,1|
+----+----+
| 1,0| 1,1|
+----+----+
| 2,0| 2,1|
+----+----+

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

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

因此在子块2,1的空间中有一个默认的轴集,其中包含记号和标签。我怎样才能用编程的方式把这个空间变成空白并且没有轴?


Tags: 数据声明matplotlib编程空间plt数字标签
3条回答

自从首次提出这个问题以来,matplotlib中添加了一个大大改进的subplot interface。在这里,您可以创建您所需的子块,而无需隐藏额外项。此外,子块可以跨越其他行或列。

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()方法隐藏子块。

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)

你可以把不需要的斧头藏起来。例如,以下代码完全转动第6轴:

import matplotlib.pyplot as plt

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

plt.show()

结果如下:

enter image description here

或者,请参阅问题Hiding axis text in matplotlib plots的已接受答案,以获取保留轴但隐藏所有轴装饰(例如记号和标签)的方法。

相关问题 更多 >