2016-12-09 50 views
1

的問題如何在matplotlib中自定義孵化範圍?

我有兩個100x100的arrays-一個與數據(我會打電話給array1)和一個與一些較小的,按比例的數據(我會打電話給array2)。我創建了一個測試數組,以查看array2 + array1高於還是低於特定閾值,並且每個點的結果應該是以下三個結果中的一個:array1 + array2該點是> 5,> 10或者都不是(< 5) 。根據結果​​,我創建了一個新的100x100陣列(array3),並分別指定了一個1.,2.或0.。

現在我想繪製array1 & array3使用plt.contourf(),我希望後者的子圖有陰影。我希望陰影的範圍是x = 0,x = 1和x = 2。看看我知道的文檔,我可能無法這樣做,所以我會說x < 1,1 < = x,< 2,並且x => 2。唯一的問題是我不知道如何指定這些範圍。

代碼(例如工作)

這裏是問題的全部代碼。

#Make data array1 
array1 = np.empty([10,10]) 
for i in range(10): 
    for j in range(10): 
     array1[i,j] = i+j 
print array1 

#Make data array2 
array2 = np.empty([10,10]) 
for i in range(10): 
    for j in range(10): 
     array2[i,j] = (i*0.25)+(j*0.25) 
print array2 

#Make range test array3 
array3 = np.empty([10,10]) 
for i in range(10): 
    for j in range(10): 
     if array1[i,j]+array2[i,j] > 5 and array1[i,j]+array2[i,j] > 10: 
      array3[i,j] = 2 
     elif array1[i,j]+array2[i,j] > 5: 
      array3[i,j] = 1 
     else: 
      array3[i,j] = 0 
print array3 

#Plot 
from matplotlib.patches import Ellipse, Polygon 
xgrid = np.arange(0,10) 
ygrid = np.arange(0,10) 
n_levels=2 
plt.contourf(xgrid, ygrid, array1) 
stip = plt.contourf(xgrid, ygrid, array3, n_levels, colors='none', 
       hatches=[None,'.', '/'], 
       extend='lower') 
#create a legend for the contour set 
artists, labels = stip.legend_elements() 
plt.legend(artists, labels, handleheight=2) 
plt.show 

enter image description here

注意的傳說。我想要的範圍是x < 1,1 < = x,< 2,並且x => 2,而不是軟件包自動分配的內容。

問題

我怎樣才能指定自定義範圍,以我的陰影?我打算讓這個例子工作,這樣我就可以將它翻譯成一個底圖,其中我有lat-lon數據,並且還有一個點陣數據,其中lat-lon數據與數據+ S.D進行比較。另外兩個陣列。我想要各種點畫,取決於每個網格點,如果該經緯度數據是>一個數據+ S.D。數組,其他數據+ S.D。數組或兩個數組。

回答

2

關於輪廓等級的更多控制,請使用levels關鍵字。

stip = plt.contourf(xgrid, ygrid, array3, levels=[-1, 0, 1, 2], 
        colors='none', hatches=[None,'.', '/']) 
artists, labels = stip.legend_elements() 
plt.legend(artists, labels, handleheight=2) 

enter image description here

+0

謝謝,你知道如何才能讓自定義圖例標籤? stip.legend_elements()這行會引發我一個循環。 – ChristineB

+0

@ChristineB標籤只是字符串或任何可以轉換爲字符串的對象,請參閱['legend()']上的文檔(http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend)和[傳奇指南](http://matplotlib.org/users/legend_guide.html)。 – Goyo