2014-06-10 5 views
1

2 개 이상의 범례가있는 플롯이 있습니다. 전설에서 범례의 색상 및 선형을 변경 (예 : 변경)하려면 어떻게해야합니까?플롯에서 모든 범례를 얻는 방법?

handles, labels = ax.get_legend_handles_labels()은 내가 "plt.legend()"으로 플롯에 추가 한 "첫 번째"범례 만 제공합니다. 하지만 나는 다른 사람들도 전설을 원한다. 나는 이것들을 어떻게 덧붙였다. plt.gca().add_artist(leg2) 어떻게 할 수 있는가?

+0

더 완벽한 예를 들려 줄 수 있습니까? 여기에 대해 당신이 무엇을 말하고 있는지 전혀 모르겠다. – tacaswell

답변

2

당신과 함께 전설 형식상의 축과 필터의 어린이를 얻을 수 있습니다 :

legends = [c for c in ax.get_children() if isinstance(c, mpl.legend.Legend)] 

하지만 전혀 그 일을합니까? 내가 언급 한 것처럼 더 많은 범례를 추가하면 여러 개의 Legend 자식이 표시되지만 모두 동일한 개체를 가리키고 있습니다.

편집 :

축은 자체가 마지막 전설이 추가 유지, 그래서 당신은 .add_artist()로 이전을 추가하는 경우, 여러 다른 전설 참조 : 예를 들어

:

fig, ax = plt.subplots() 

l1, = ax.plot(x,y, 'k', label='l1') 
leg1 = plt.legend([l1],['l1']) 

l2, = ax.plot(x,y, 'k', label='l2') 
leg2 = plt.legend([l2],['l2']) 

ax.add_artist(leg1) 

print(ax.get_children()) 

반환이를 개체 :

[<matplotlib.axis.XAxis at 0xd0e6eb8>, 
<matplotlib.axis.YAxis at 0xd0ff7b8>, 
<matplotlib.lines.Line2D at 0xd0f73c8>, 
<matplotlib.lines.Line2D at 0xd5c1a58>, 
<matplotlib.legend.Legend at 0xd5c1860>, 
<matplotlib.legend.Legend at 0xd5c4b70>, 
<matplotlib.text.Text at 0xd5b1dd8>, 
<matplotlib.text.Text at 0xd5b1e10>, 
<matplotlib.text.Text at 0xd5b1e48>, 
<matplotlib.patches.Rectangle at 0xd5b1e80>, 
<matplotlib.spines.Spine at 0xd0e6da0>, 
<matplotlib.spines.Spine at 0xd0e6ba8>, 
<matplotlib.spines.Spine at 0xd0e6208>, 
<matplotlib.spines.Spine at 0xd0f10f0>] 

이것이 당신이하고 싶은 일인지 여부!? 또한 축과 별도로 선 (또는 다른 유형)을 직접 저장할 수도 있습니다.

+0

'legends = [isinstance (c, mpl.legend.Legend)] '가 ax.get_children()에있는 c를위한 c'는 훌륭한 작품이다! 플롯에서 모든 전설을 돌려줍니다! 그게 정확히 내가 찾고 있던거야! 고마워요! – Hubschr

관련 문제