2017-03-13 22 views
3

我目前使用下面的代碼塊解決了我的問題。它做我想要的,但是有很多代碼重複,並且有點難以閱讀。如何管理創建,添加數據和顯示多個matplotlib數字?

我有幾個數字,我想創建並填充在一個大的循環中計算的數據。

我很難搞清楚在我的代碼頂部創建和設置標題/元數據的語法,然後將所有正確的數據添加到我的代碼底部的正確數字。

我有這樣的:

import matplotlib.pyplot as plt 
import numpy as np 
figure = plt.figure() 
plt.title("Figure 1") 
figure.add_subplot(2,2,1) 
plt.imshow(np.zeros((2,2))) 
# Some logic in a for loop to add subplots 
plt.show() 

figure = plt.figure() 
plt.title("Figure 2") 
figure.add_subplot(2,2,1) 
# Some Logic in an identical for loop to add different subplots 
plt.imshow(np.zeros((2,2))) 
plt.show() 

我想要的東西,看起來更像是這樣的:

# Define variables, titles, formatting, etc. 
figure = plt.figure() 
figure2 = plt.figure() 
figure1.title = "Figure 1" 
figure2.title = "Figure 2" 

# Populate 
figure.add_subplot(2,2,1) 
figure2.add_subplot(2,2,1) 
# Some logic in a for loop to add subplots to both figures 

有沒有乾淨的方式做什麼,我與matplotlib問?我主要是想清理我的代碼,並有一個更容易擴展和維護的程序。

我真的只是想要一種方法來定義我的所有數字和標題在一個地方,然後根據其他邏輯將圖像添加到正確的數字。能夠爲特定的數字調用plt.show()也很好。

回答

1

爲了在代碼中的不同位置處理不同的圖形,最簡單的方法是保留所有圖形的引用。同樣保持對各個軸的參考對於能夠繪製它們是有用的。

import matplotlib.pyplot as plt 

figure = plt.figure(1) 
figure2 = plt.figure(2) 
figure.title("Figure 1") 
figure2.title("Figure 2") 

ax1 = figure.add_subplot(2,2,1) 
ax2 = figure2.add_subplot(2,2,1) 
ax999 = figure2.add_subplot(2,2,4) 

ax1.plot([2,4,1]) 
ax2.plot([3,0,3]) 
ax999.plot([2,3,1]) 

plt.show() 

plt.show()應該總是在最後被調用。然後它會繪製所有未結數字。要僅顯示一些數字,則需要編寫自定義show函數。在致電plt.show之前,此功能只是關閉所有不需要的數字。

import matplotlib.pyplot as plt 

def show(fignums): 
    if isinstance(fignums, int): 
     fignums = [fignums] 
    allfigs = plt.get_fignums() 
    for f in allfigs: 
     if f not in fignums: 
      plt.close(f) 
    plt.show() 


figure = plt.figure(1) 
figure2 = plt.figure(2) 
figure.title("Figure 1") 
figure2.title("Figure 2") 

ax1 = figure.add_subplot(2,2,1) 
ax2 = figure2.add_subplot(2,2,1) 

ax1.plot([2,4,1]) 
ax2.plot([3,0,3]) 

show([1, 2]) 

可能互斥的方式來調用show現在是

show(1) # only show figure 1 
show(2) # only show figure 2 
show([1,2]) # show both figures 
show([]) # don't show any figure 

請注意,您仍然可以在腳本的末尾調用show只有一次。

1

把你的人物的名單,並通過它瀏覽人數超過他們:如果需要,您可以在第一個循環繪製

import matplotlib.pyplot as plt 
import numpy as np 

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

# set up figures 
figures = [] 
for ind in xrange(1,4): 
    f = plt.figure() 
    figures.append(f) 
    f.title = "Figure {0:02d}".format(ind) 

# Populate with subplots 
figures[0].add_subplot(2,2,1) 
figures[1].add_subplot(2,2,1) 

# select first figure 
plt.figure(1) 
# get current axis 
ax = plt.gca() 
ax.plot(t, s2, 's') 

# select 3rd figure 
plt.figure(3) 
ax = plt.gca() 
ax.plot(t, s1, 's') 

plt.show() 

。 關閉數字使用plt.close(figures[0])