2013-05-17 171 views
4

我正在繪製使用集合的圓形組,並且無法生成三個類別的圖例。我想:在matplotlib中使用PathCollections的圖例

  • 貓1:紅色圓圈
  • 貓2:藍色圓圈
  • 3類:黃色圓圈
import matplotlib 
import matplotlib.pyplot as plt 
from matplotlib.collections import PatchCollection 
from matplotlib.patches import Circle 
import numpy as np 

# (modified from one of the matplotlib gallery examples) 
resolution = 50 # the number of vertices 
N = 50 
Na = 25 
Nb = 10 
x  = np.random.random(N) 
y  = np.random.random(N) 
radii = 0.1*np.random.random(30) 

xa  = np.random.random(Na) 
ya  = np.random.random(Na) 
radiia = 0.1*np.random.random(50) 


xb  = np.random.random(Nb) 
yb  = np.random.random(Nb) 
radiib = 0.1*np.random.random(60) 

patches = [] 
patchesa = [] 
patchesb = [] 
for x1,y1,r in zip(x, y, radii): 
    circle = Circle((x1,y1), r) 
    patches.append(circle) 

for x1,y1,r in zip(xa, ya, radiia): 
    circle = Circle((x1,y1), r) 
    patchesa.append(circle) 

for x1,y1,r in zip(xb, yb, radiib): 
    circle = Circle((x1,y1), r) 
    patchesb.append(circle) 


fig = plt.figure() 
ax = fig.add_subplot(111) 

colors = 100*np.random.random(N) 
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4, label= "Cat 1", facecolor="red") 
pa = PatchCollection(patchesa, cmap=matplotlib.cm.jet, alpha=0.3, label= "Cat 2", facecolor="blue") 
pb = PatchCollection(patchesb, cmap=matplotlib.cm.jet, alpha=0.4, label= "Cat 3", facecolor="yellow") 
#p.set_array(colors) 
ax.add_collection(p) 
ax.add_collection(pa) 
ax.add_collection(pb) 
ax.legend(loc = 2) 
plt.colorbar(p) 

print p.get_label() 

plt.show() 

PathCollection s爲沒有可迭代的對象,所以試圖生成傳說如下;

legend([p, pa, pb], ["cat 1", "2 cat", "cat 3"]) 

不起作用。

標題如何出現?

我的系統上的Python 2.7和Matplotlib 1.2.0_1

注意運行該命令print p.get_label()顯示對象具有相關聯的標籤,但matplotlib是無法安裝的傳說。

+0

http://matplotlib.org/users /legend_guide.html#using-proxy-artist – tacaswell

回答

6

一種可能的解決方案是添加Line2D對象以用於圖例,也稱爲使用代理藝術家。要做到這一點,你必須添加from matplotlib.lines import Line2D到您的腳本,然後你可以將這段代碼:

ax.legend(loc = 2) 
plt.colorbar(p) 

print p.get_label() 

與此:

circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize=10, markerfacecolor="red") 
circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.3, markersize=10, markerfacecolor="blue") 
circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize=10, markerfacecolor="yellow") 

plt.legend((circ1, circ2, circ3), ("Cat 1", "Cat 2", "Cat 3"), numpoints=1, loc="best") 

enter image description here

+0

太好了,我更關心如何找到啓用圖例的方法,使用patchcollections並沒有想到一個簡單的方法來解決我的問題。 – Daeron

+0

@Daeron如果這解決了你的問題,請[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235)所以你的問題是標記爲_solved_供將來參考,以及爲我們提供一些聲譽! – hooy