2016-09-30 47 views
0

显示图例我有使用以下代码段底图绘制:在Matplotlib底图

#setting the size 
plt.figure(figsize=(20,10)) 
#iterating through each country in shape file and filling them with color assigned using the colors array 
for nshape,seg in enumerate(m.countries): 
#getting x,y co-ordinates 
    xx,yy = zip(*seg) 
#getting the corresponding color 
    color = colors[countryisos[nshape]] 
#plotting them on the map 
    plt.fill(xx,yy,color,edgecolor=color) 
#setting the parallels with 10 degree interval from -90 to 90 degrees 
parallels = np.arange(-80.,81,10.) 
m.drawparallels(parallels,labels=[True,True,True,True]) 
#setting the meridians with 20 degree interval from -180 to 180 degrees 
meridians = np.arange(10.,351.,20.) 
m.drawmeridians(meridians,labels=[True,False,False,True]) 
#setting the title for the plot 
plt.title('Number of Disasters by Country: 1981-2014') 

三种颜色被分配给使用该功能的颜色阵列。

colors={} 
#iterating through each country in shape file and setting the corresponding color 
for s in countryisos: 
    if countvalues[s]<=200: 
     colors[s] = 'orange' 
    elif countvalues[s]>200 and countvalues[s]<=400: 
     colors[s] = 'yellow' 
    else: 
     colors[s] = 'red' 

如何设置该图的图例,显示三种颜色,每种颜色定义一个范围?因为它在for循环中,所以我不能在plot函数中使用'label'参数。

回答

2

使用matplotlib中的补丁来解决它。我只是在下面添加了以下代码来显示自定义图例。

#setting the legend for the plot using patch 
lt = mpatches.Patch(color='orange', label='<200') 
btwn = mpatches.Patch(color='yellow', label='200-400') 
gt = mpatches.Patch(color='red', label='>400') 
plt.legend(handles=[lt,btwn,gt],title='Number of disasters', loc=3)