2010-08-11 33 views
1

我正在繪製一些研究項目的天氣數據。情節包括18個時間步。我決定實現這一目標的最佳方法是爲每個時間步創建一個新的情節,將其保存爲一個文件,併爲下一個時間步創建新的情節(使用for循環)。繪製在一個循環(與底圖和pyplot)....問題與pyplot.clf()

例如:


map_init #[Basemap Instance] 
extra_shapes #[Basemap.readshapefile object] 

for i in range(timesteps): 
    #plot the weather data for current timestep to current plot 
    map_init.imshow(data[i]) 

    # extra_shapes are county boundaries. Plot those as polygons 
    pyplot.Polygon(map_init.extra_shapes[i]) 

    # Plot the state boundaries (in basemap) 
    map_init.drawstates() 

    # add a colorbar 
    pyplot.colorbar() 

    # Save the figure 
    pyplot.savefig(filepath) 

    #close figure and loop again (if necessary) 
    pyplot.clf() 

問題在於pyplot.clf()

代碼工作,除了一兩件事。只有第一個陰謀如預期出現。每一個後續的陰謀缺少extra_shapes(即沒有縣界限)。我不明白pyplot.clf()的存在與pyplot.Polygon()的失敗之間的關係?

如果刪除,則繪製extra_shapes,但每個圖都有多個顏色條(取決於i的值)。 pyplot.clf()的唯一原因是避免在最終情節中有18個顏色條。有沒有辦法強制每個圖只有一個顏色條?

+0

原始循環背後的邏輯是一個相當倉促的嘗試,使每個時間步完全分開的圖。 最初,map_init是在循環內部以及extra_shapes中分配的。 extra_shapes是一個相當大的數據集(因爲它包含美國和相關地區的每個縣的邊界)。爲循環的每次迭代分配extra_shapes變得非常耗時(與map_init相同)。所以把這兩個任務移到循環之外,一切都打破了。 – ayr0 2010-08-11 21:07:05

回答

3

嘗試製作一個新圖而不是使用clf()。

例如

for i in range(timesteps): 
    fig = pyplot.figure() 
    ... 
    fig.savefig(filepath) 

或者(和更快),你簡直在您的圖像對象 更新數據(通過imshow()返回)。

例如(完全未經測試):

map_init #[Basemap Instance] 
extra_shapes #[Basemap.readshapefile object] 


#plot the weather data for current timestep to current plot 
img = map_init.imshow(data[0]) 

# extra_shapes are county boundaries. Plot those as polygons 
plygn = pyplot.Polygon(map_init.extra_shapes[0]) 

# Plot the state boundaries (in basemap) 
map_init.drawstates() 

# add a colorbar 
pyplot.colorbar() 

for i in range(timestamps): 
    img.set_data(data[i]) 
    plygn.set_xy(map_init.extra_shapes[i]) 
    pyplot.draw() 
    pyplot.savefig(filepath) 

但是,有可能該方法可能無法在底圖中很好地發揮作用。我也可以記錯正確的方式重新繪製的數字,但我相當肯定,它只是plt.draw()...

希望有點幫助反正

編輯:剛纔注意到你」重新繪製一個循環內的多邊形,以及。更新了第二個例子以正確反映這一點。

+0

非常感謝您的幫助。 我無法讓我的原始循環按預期工作(即使有您的第一個示例中的建議)。 然而,第二個例子就像一個魅力。它實際上比我原來的循環更有意義。 img數據實際上是每個時間步長之間唯一改變的數據。 ps。看到上面編輯的問題 – ayr0 2010-08-11 21:04:02