2012-04-05 129 views
44

我在matplotlib中創建了一組子圖(比如3 x 2),但是我的數據集少於6個。我怎樣才能使剩餘的子空間變爲空白?如何在matplotlib中創建空白子圖?

的安排是這樣的:

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

這可能會持續幾頁,但在最後一頁上,有,例如,5個集的2,1箱是空的。不過,我宣佈這個數字爲:

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

所以在空間插曲2,1有蜱和標籤軸的默認設置。我怎樣才能以編程方式將該空間呈現爲空白並且沒有座標軸?

回答

73

你總是可以隱藏你不需要的軸。例如,下面的代碼完全變爲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用於保持軸線但隱藏所有軸裝飾(例如刻度線和標籤)的方式。

+0

謝謝 - 這實際上更接近我原來的問題。我已經接受了其他答案,並調整了我的代碼來使用它,但兩種方法都很棒。 – mishaF 2012-04-05 21:06:23

+0

很酷,這確實很不錯,因爲'add_subplot()'雜亂。第二個想法的 – moooeeeep 2012-04-05 21:12:28

+1

- 這樣更合適,我轉換.... – mishaF 2012-04-10 02:22:25

1

當你需要的時候創建子圖會不會是一個選項?

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") 
+0

我不這麼認爲,因爲還有其他格式化的東西我需要做,因爲我沒有在原始問題中包含簡潔。其中之一是plt.subplots_adjust(wspace = 0,hspace = 0)。事實之後,我不確定這會起作用。 – mishaF 2012-04-05 20:44:52

+0

@mishaF:你可以使用這種方法做subplots_adjust()。看我的編輯。 – moooeeeep 2012-04-05 20:54:21

+0

果然 - 工作正常!謝謝噸! – mishaF 2012-04-05 20:57:14

13

A 很多改進subplot interface已被添加到matplotlib中,因爲這個問題首次被問到。在這裏,您可以創建完全所需的子圖,而無需隱藏額外信息。另外,子圖可以跨越額外的行或列。

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

+0

哇 - 這是一個很好的改進。非常簡單!謝謝@Hooked! – mishaF 2013-01-24 21:56:25

0

它也有可能隱藏使用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)