2009-09-16 48 views
10

我在這個有點新手,並試圖創建與自定義氣泡大小和顏色的散點圖。圖表顯示正常,但我如何得到一個圖例說明顏色是指什麼。這是據我已經有了:Matplotlib傳說與自定義顏色分散

inc = [] 
out = [] 
bal = [] 
col = [] 

fig=Figure() 
ax=fig.add_subplot(111) 

inc = (30000,20000,70000) 
out = (80000,30000,40000) 
bal = (12000,10000,6000) 
col = (1,2,3) 
leg = ('proj1','proj2','proj3') 

ax.scatter(inc, out, s=bal, c=col) 
ax.axis([0, 100000, 0, 100000]) 

ax.set_xlabel('income', fontsize=20) 
ax.set_ylabel('Expenditure', fontsize=20) 
ax.set_title('Project FInancial Positions %s' % dt) 
ax.grid(True) 
canvas=FigureCanvas(fig) 
response=HttpResponse(content_type='image/png') 
canvas.print_png(response) 

該線程是有益的,但不能把它解決我的問題:Matplotlib: Legend not displayed properly

回答

9

也許這個example是有幫助的。

一般來說,在圖例中的項目與某種繪製對象有關。所述scatter功能/方法治療各界作爲單個對象,請參見:

print type(ax.scatter(...)) 

因此,解決方案是創建多個對象。因此,多次撥打scatter

不幸的是,較新版本的matplotlib似乎並未在圖例中使用矩形。因此,圖例將包含非常大的圓,因爲您增加了散點圖對象的大小。

圖例函數作爲markerscale關鍵字參數來控制圖例標記的大小,但它似乎被打破。

更新:

Legend guide建議在類似案件中使用Proxy ArtistColor API解釋了有效的fc值。

p1 = Rectangle((0, 0), 1, 1, fc="b") 
p2 = Rectangle((0, 0), 1, 1, fc="g") 
p3 = Rectangle((0, 0), 1, 1, fc="r") 
legend((p1, p2, p3), ('proj1','proj2','proj3')) 

要獲得一個情節以前使用的顏色,使用像上面的例子:

pl1, = plot(x1, y1, '.', alpha=0.1, label='plot1') 
pl2, = plot(x2, y2, '.', alpha=0.1, label='plot2') 
p1 = Rectangle((0, 0), 1, 1, fc=pl1.get_color()) 
p2 = Rectangle((0, 0), 1, 1, fc=pl2.get_color()) 
legend((p1, p2), (pl1.get_label(), pl2.get_label()), loc='best') 

這個例子將作出這樣一個情節:

Matplotlib with custom legend

+0

好的解決方案,即使由於破損的刻度尺而不起作用。 – tom10

+0

這個例子非常有幫助。必須去做一些適當的工作,但今天晚上會回來。 – PhoebeB