2014-02-13 3 views
1

이것은 중복 된 것처럼 보일 수 있지만 호환되는 답변을 찾으려고했습니다.matplotlib에서 서브 플롯 세트에 대해 단일 범례를 정의하는 방법은 무엇입니까?

동일한 3 개의 샘플에 대해 서로 다른 속성의 히스토그램을 가지고 있습니다. 그래서이 나무 샘플의 이름을 가진 전설이 필요합니다.

I는 다음과 같이, 모든 히스토그램에서 동일한 라벨을 ('H1', 'H2'및 'H3')를 형성하려고

:

plt.subplot(121) 
plt.hist(variable1[sample1], histtype = 'step', normed = 'yes', label = 'h1') 
plt.hist(variable1[sample2], histtype = 'step', normed = 'yes', label = 'h2') 
plt.hist(variable1[sample3], histtype = 'step', normed = 'yes', label = 'h3') 

plt.subplot(122) 
plt.hist(variable2[sample1], histtype = 'step', normed = 'yes', label = 'h1') 
plt.hist(variable2[sample2], histtype = 'step', normed = 'yes', label = 'h2') 
plt.hist(variable2[sample3], histtype = 'step', normed = 'yes', label = 'h3') 
이어서

I 사용 :

plt.legend(['h1', 'h2', 'h3'], ['Name Of Sample 1', 'Name Of Sample 2', 'Name Of Sample 3'],'upper center') 

범례 나타나지만 비어 있습니다. 어떤 아이디어?

답변

1

두 가지 문제가 있습니다. 첫 번째는 당신이 오해하고 있다는 것입니다. 무엇이 label입니다. 이 이름으로 액세스 할 수있는 아티스트는 표시하지 않지만 어떤 경우에도 을 호출하면 이 사용하는 텍스트를 제공합니다. 두 번째 문제는 bar에 자동 생성 범례 처리기가 없다는 것입니다.

fig, (ax1, ax2) = plt.subplots(1, 2) 

h1 = ax1.hist(variable1[sample1], histtype='step', normed='yes', label='h1') 
h2 = ax1.hist(variable1[sample2], histtype='step', normed='yes', label='h2') 
h3 = ax1.hist(variable1[sample3], histtype='step', normed='yes', label='h3') 

ha = ax2.hist(variable2[sample1], histtype='step', normed='yes', label='h1') 
hb = ax2.hist(variable2[sample2], histtype='step', normed='yes', label='h2') 
hc = ax2.hist(variable2[sample3], histtype='step', normed='yes', label='h3') 

# this gets the line colors from the first set of histograms and makes proxy artists 
proxy_lines = [matplotlib.lines.Line2D([], [], color=p[0].get_edgecolor()) for (_, _, p) in [h1, h2, h3]] 

fig.legend(proxy_lines, ['label 1', 'label 2', 'label 3']) 

또한 프록시 아티스트를 모르는

+0

@zhangxaochen 믿을 수 없을만큼 강력하고 멋지지만 전설적인 코드는 믿을 수 없을 정도로 불투명합니다. 핸들러 파견을하는 방법을 살펴보십시오. 놀라운 일을 할 수 있습니다. – tacaswell

관련 문제