2017-02-19 78 views
4

我在演示如何在數字之間來回切換的示例腳本。我在這裏找到了這個例子:http://matplotlib.org/examples/pylab_examples/multiple_figs_demo.html當我試圖打印出圖號時,我得到了「圖(640x480)」,而不是我期待的數字1。你怎麼得到這個號碼?如何在Python的matplotlib中獲得當前的圖號?

# Working with multiple figure windows and subplots 
import matplotlib.pyplot as plt 
import numpy as np 

t = np.arange(0.0, 2.0, 0.01) 
s1 = np.sin(2*np.pi*t) 
s2 = np.sin(4*np.pi*t) 

plt.figure(1) 
plt.subplot(211) 
plt.plot(t, s1) 
plt.subplot(212) 
plt.plot(t, 2*s1) 

plt.figure(2) 
plt.plot(t, s2) 

# now switch back to figure 1 and make some changes 
plt.figure(1) 
plt.subplot(211) 
plt.plot(t, s2, 's') 
ax = plt.gca() 
ax.set_xticklabels([]) 

# Return a list of existing figure numbers. 
print "Figure numbers are = " + str(plt.get_fignums()) 
print "current figure = " + str(plt.gcf()) 
print "current axes = " + str(plt.gca()) 

plt.show() 

這裏是輸出:

Figure numbers are = [1, 2] 
current figure = Figure(640x480) 
current axes = Axes(0.125,0.53;0.775x0.35) 

回答

6

Figure對象有一個number屬性,因此你可以通過

>>> plt.gcf().number 
+0

是的,這工作獲得的數量。你怎麼知道的?即使知道如何去做,我也找不到任何文件。 –

+0

您也可以使用文本字符串而不是數字創建圖形,例如plt.figure(「first」)。在數字之間切換時,這可能比數字更容易記住。仍然plt.gcf()。數字給出整數「1」,所以它必須是一個自動編號。 –

+0

@ R.Wayne說實話,我以前並不知道,但我認爲有這樣一個屬性(我認爲術語「受過教育的猜測」適用得非常好)。所以我檢查了'dir(plt.gcf())',它揭示了'number'屬性。 'help(pyplot.figure)'提供了以下信息:_ [...] figure對象將這個數字保存在一個'number'屬性中._通常檢查'dir(...) '在你想要從中檢索屬性的任何對象上。 'help(...)'通常也是有用的! –