【问题标题】:Matplotlib Legends in For LoopFor 循环中的 Matplotlib 图例
【发布时间】:2016-03-16 17:00:58
【问题描述】:

我正在对数据进行分箱并将其绘制在地图上,每个分箱都有一个图例,但每次我通过循环时,我的图例中都会出现一条线。对于每个分箱类别,我怎样才能在我的图例中只获得一行?

注意:我有单独的 for 循环,以确保较小的圆圈绘制在较大的圆圈之上。

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()

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    您可以通过为每个类别设置一个标签来避免这种情况。 例如在第一个循环中:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      相关资源
      最近更新 更多