2017-06-13 84 views
-2

我使用histogram2D,contourf和matplotlib從csv文件繪製密度圖。 請看看我的結果: enter image description here在matplotlib中自定義圖例的間隔

所以,我的主要要求是豪定製我的傳說的間隔,我需要有僅有5間隔0.8例如一步,當涉及到我希望它只是在用相同的顏色間隔和「2.5及以上的標記間隔> 2.5 這裏是我使用定製我的傳說代碼:

cmap = plt.cm.get_cmap('Paired', 8) 
cs = m.contourf(xi, yi, g, cmap = cmap) 
cbar = plt.colorbar(cs, orientation='horizontal') 
cbar.set_label('la densite des impacts foudre',size=18) 

# Set borders in the interval [0, 1] 
bound = np.linspace(0, 1, 9) 
# Preparing borders for the legend 
bound_prep = np.round(bound * 7, 2) 
# Creating 8 Patch instances 
plt.legend([mpatches.Patch(color=cmap(b)) for b in bound[:-1]], 
     ['{} - {}'.format(bound_prep[i], bound_prep[i+1] - 0.01) for i in range(8)], bbox_to_anchor=(1.05, 1), loc=2) 
plt.gcf().set_size_inches(15,15) 
plt.show() 

所以基本上我需要類似的傳說到這一個:

enter image description here

任何想法?

+0

我有問題,瞭解您所期望的結果。你說你想要有5個區間,但已經在代碼中有8個區間。此外,如果間隔爲0.8,則只能得到3,第八個間隔可達2.5。間隔中的顏色應該如何與等值線圖的顏色相關? – ImportanceOfBeingErnest

+0

很明顯,你真的理解我期望的結果,所以是的,我有8個間隔,但我需要管理,以保持只有6或5間隔低於0.8的步驟,當然間隔高達2.5應該在一個總結區間稱爲2.5及以上,並具有獨特的顏色。 –

回答

1

我不確定,如果我現在正確地理解了一切。對我來說,只有在圖例中顯示的圖中使用完全相同數量的層次纔有意義。

當然,您可以通過參數contourflevels參數手動選擇要使用的級別。

import matplotlib.pyplot as plt 
import numpy as np 

x= np.linspace(-3,3) 
X,Y = np.meshgrid(x,x) 
Z = np.exp(-(X**2+Y**2)) 

levels = [0,.1,.2,.3,.4,.5,1] 
cmap=plt.cm.get_cmap("Paired") 
colors=list(map(cmap, range(len(levels)))) 


fig,ax=plt.subplots() 
cf = ax.contourf(X,Y,Z, levels=levels, colors=colors) 
fig.colorbar(cf) 

handles = [plt.Rectangle((0,0),1,1, color=c) for c in colors] 
labels = [u"de {} à {}".format(levels[i], levels[i+1]) for i in range(len(levels)-1)] 
labels[-1] = "plus de {}".format(levels[-2]) 
ax.legend(handles, labels) 

plt.show() 

enter image description here

+0

是啊,這就是我一直在尋找的,非常感謝你的幫助! –