2017-01-23 12 views
0

으로 상이한 크기 및 색상 각 (마커 ',', 'o', '*''^'이다).하기 matplotlib 산점도 범례 내가 산점도 4 개 심볼 플롯 <code>ax.scatter(x,y,c=color, s=size, marker='*', label="mylabel")</code> 사용하고 별도의 이미지

나는 ax.legend()을 호출 해 보았습니다. 그리고 예상되는 레이블 정보를 얻었지만, 범례에는 아무 것도 표시되지 않았습니다. 여기에 설명 된 많은 변형을 사용해 보았습니다. http://matplotlib.org/users/legend_guide.html

또한 전적으로 내 전설이 완전히 다른 이미지로 존재해야합니다. Get legend as a separate picture in Matplotlib

https://pymorton.wordpress.com/2016/04/05/creating-separate-legend-figure-with-matplotlib/

을하지만 마커를 표시 할 수 없었다 : 나는 노력했다. 모든 조언을 부탁드립니다!

import matplotlib.pyplot as plt 
import matplotlib.colors as colors 
import numpy as np 
from scipy import stats 

lat = np.random.randint(-60.5, high=60.5, size=257087) 
lon = np.random.randint(-179.95, high=180, size=257087) 
thiscategory = np.random.randint(12, 60, size=257087) 

percRange = np.arange(100,40,-1) 


#Rank all values 
allPercent=stats.rankdata(thiscategory)/len(thiscategory) 

h=np.where(allPercent > 0.9) 
hl=np.where((allPercent <= 0.9) & (allPercent > 0.8)) 
mh=np.where((allPercent <= 0.8) & (allPercent > 0.7)) 
ml=np.where((allPercent <= 0.7) & (allPercent > 0.6)) 
l=np.where(allPercent <= 0.6) 

allPercent[h]=0 
allPercent[hl]=0.25 
allPercent[mh]=0.5 
allPercent[ml]=0.75 
allPercent[l]=1 


fig = plt.figure(dpi=400) 
ax=fig.add_axes([0,0,1,1]) #position: left, bottom, width, height 
ax.set_axis_off() 
fig.patch.set_facecolor('none') 

latcorners = ([-90.0,90.0]) 
loncorners = ([-180.0,180.0]) 


rgba_low=colors.hex2color('#e0ffff') #224-255-255 Light Cyan 
rgba_ml=colors.hex2color('#afeeee') #175-238-238 Pale Turquoise 
rgba_mh=colors.hex2color('#ffff00') #Yellow 
rgba_hl=colors.hex2color('#ffa500') #Orange 
rgba_high=colors.hex2color('#f8f8ff') #ghost white 

m = Basemap(projection='cyl',llcrnrlat=latcorners[0],urcrnrlat=latcorners[1],llcrnrlon=loncorners[0],urcrnrlon=loncorners[1])      
# Draw on map. 
x, y = m(lon, lat) 



ax.scatter(x[ml],y[ml], c=rgba_ml, s=3, marker=',',edgecolor='none', alpha=0.4, label=str(mlmin)+" to "+str(mlmax)) 
ax.scatter(x[mh],y[mh], c=rgba_mh, s=5, marker='o', edgecolor='none', alpha=0.5, label=str(mhmin)+" to "+str(mhmax)) 
ax.scatter(x[hl],y[hl], c=rgba_hl, s=10, marker='*',edgecolor='none', alpha=0.6, label=str(hlmin)+" to "+str(hlmax)) 
ax.scatter(x[h],y[h], c=rgba_high, s=20, marker='^', edgecolor='none',alpha=0.7, label=str(hmin)+" to "+str(hmax)) 

ax.set_xlim([-180,180]) 
ax.set_ylim([-90,90]) 

#this is where my legend calls were going, but since I want them in a new plot it doesn't seem appropriate 


fig.savefig('testfig.jpg', bbox_inches='tight', transparent=True, pad_inches=0) 

* 샘플 코드를 보여 편집 :

여기 내 플로팅 코드입니다.

+1

"내 컴퓨터가 작동하지 않습니다"라는 사람에게 전화하는 것과 같습니다. 잘못되었을 수있는 일이 너무 많습니다. 따라서이 문제에 대한 도움을 얻기 위해 사용한 코드를 게시해야합니다. 당신이 그것을 묘사하는 방식은 효과가있을 것이므로, 코드에서 어딘가에 [MCVE]를 얻을 때 도움이 될만한 문제가 있어야합니다. – ImportanceOfBeingErnest

+0

내가 알지 못하는 산포도 속성이있는 경우에 대비하여 공개 된 상태로 유지하고 싶었습니다. 플로팅 코드를 게시하도록 편집합니다. – mofs

+1

'ax.legend()'를 추가하면 마커를 포함한 범례가 표시됩니다. 당신은 [링크 된 질문] (http://stackoverflow.com/questions/4534480/get-legend-as-a-separate-picture-in-matplotlib)에서 언급 된 명령을 적용하지 않기 때문에 별도의 파일, 왜 그런 일이 일어날 것이라고 기대합니까? 마지막으로, [MCVE]에서 최소한, 완전하고 검증 가능한 단어가 무엇인지 생각해보십시오! – ImportanceOfBeingErnest

답변

1

다음은 내가 찾은 것입니다. 그림 호출을 포함하지 않도록 찾은 코드를 수정해야했습니다. 메인 플롯을 플롯과 나는 새로운 그림이라는 그림 닫은 후

handles,labels = ax.get_legend_handles_labels() 

을 : 산란 (ax.scatter)을 플로팅 후에 나는라고

fig_legend = plt.figure(figsize=(2,2)) 
axi = fig_legend.add_subplot(111)    
fig_legend.legend(handles, labels, loc='center', scatterpoints = 1) 
axi.xaxis.set_visible(False) 
axi.yaxis.set_visible(False) 
fig_legend.canvas.draw() 
fig_legend.show() 

최종 결과는 두 개의 검은 색 테두리를 포함,하지만 그것은 별도의 이미지이며 정확한 색상의 스 캐터 심볼의 단일 인스턴스를가집니다. legend image example here