简体   繁体   中英

Matplotlib Legends in For Loop

I'm binning data and plotting it on a map with a legend for each bin, but I get a line in my legend for each time I go through the loop. How can I just get one line in my legend for each binned category?

NOTE: I have separate for loops to ensure that the smaller circles plot on top of the bigger circles.

在此处输入图片说明

sigcorrs = np.random.rand(100,1)

m = Basemap(llcrnrlon=35.,llcrnrlat=30.,urcrnrlon=-160.,urcrnrlat=63.,projection='lcc',resolution='c',lat_1=20.,lat_2=40.,lon_0=90.,lat_0=50.)  
m.drawcountries()
m.drawmapboundary(fill_color='lightblue')
m.drawparallels(np.arange(0.,90.,5.),color='gray',dashes=[1,3],labels=[1,0,0,0])
m.drawmeridians(np.arange(0.,360.,15.),color='gray',dashes=[1,3],labels=[0,0,0,1])
m.fillcontinents(color='beige',lake_color='lightblue',zorder=0)
plt.title('Mean Absolute Error')

for a in range(len(clat)):
    if sigcorrs[a] > 0.8:
        X,Y = m(clon[a],clat[a])  
        m.scatter(X,Y,s=300,label='Corr > 0.8')
    else:
        continue

for a in range(len(clat)):
    if sigcorrs[a] > 0.6 and sigcorrs[a] <= 0.8:
        X,Y = m(clon[a],clat[a])  
        m.scatter(X,Y,s=200,label='Corr > 0.6')
    else:
        continue

for a in range(len(clat)):
    if sigcorrs[a] > 0.4 and sigcorrs[a] <= 0.6:
        X,Y = m(clon[a],clat[a])  
        m.scatter(X,Y,s=100,label='Corr > 0.4')
    else:
        continue

for a in range(len(clat)):
    if sigcorrs[a] <= 0.4:
        X,Y = m(clon[a],clat[a])  
        m.scatter(X,Y,s=50,label='Corr < 0.4')
    else:
        continue

plt.legend()
plt.show()

You can avoid this by setting only one label per category. For example in the first loop:

label_added =False
for a in range(len(clat)):
if sigcorrs[a] > 0.8:
    X,Y = m(clon[a],clat[a])  
    if not label_added:
        m.scatter(X,Y,s=300,label='Corr > 0.8')
        label_added = True
    else:
        m.scatter(X,Y,s=300)
else:
    continue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM