当前位置:   article > 正文

Matplotlib配置图例legend()设置透明和并排显示

Matplotlib配置图例legend()设置透明和并排显示

1.多排显示

  1. x=np.linspace(start=-np.pi,stop=np.pi,num=300)
  2. plt.style.use('classic')
  3. Fig,Axes=plt.subplots(1)
  4. Axes.plot(x,np.sin(x),'-b',label='Sine')
  5. Axes.plot(x,np.cos(x),'--r',label='Cosine')
  6. Axes.axis('equal')
  7. Axes.legend(loc='lower center',frameon=False,ncol=2)
  8. plt.show()

2.指定frameon参数来设定边框

默认情况下图例的边框是开启的,我们可以指定frameon参数来取消边框

  1. x=np.linspace(start=-np.pi,stop=np.pi,num=300)
  2. plt.style.use('classic')
  3. Fig,Axes=plt.subplots(1)
  4. Axes.plot(x,np.sin(x),'-b',label='Sine')
  5. Axes.plot(x,np.cos(x),'--r',label='Cosine')
  6. Axes.axis('equal')
  7. Axes.legend(loc='lower center',frameon=False)
  8. plt.show()

3.在图例中显示不同尺寸的点

下面我们将以加利福尼亚州所有城市的数据(提取码666)为例来绘图,最终效果是将绘制出各个城市的位置,同时以城市面积大小来使用不同大小的圆表示

  1. cities=pd.read_csv('california_cities.csv')
  2. latitude,longitude=cities['latd'],cities['longd']
  3. population,area=cities['population_total'],cities['area_total_km2']
  4. plt.scatter(latitude,longitude,label=None,c=np.log10(population),cmap='viridis',s=area,linewidths=0,alpha=0.5)
  5. plt.axis(aspect='euqal')a
  6. plt.xlabel('Logitude')
  7. plt.ylabel('Latitude')
  8. plt.colorbar(label='log_{10}$(population)')
  9. plt.clim(3,7)
  10. for area in [100,300,500]:
  11. plt.scatter([],[],c='k',alpha=0.3,s=area,label=str(area)+' km$^2$')
  12. plt.legend(scatterpoints=1,frameon=False,labelspacing=1,title='City Area')
  13. plt.title('California Cities : Area and Population')
  14. plt.show()

 

  1. La=1
  2. for color in list('cmyk'):
  3. plt.scatter([],[],c=color,s=100,label=La)
  4. La+=1
  5. plt.legend(frameon=False)
  6. plt.show()

同时显示多个图例

有的时候,由于排版问题,我们可能需要在同一张图像上显示多个图例.但是用Matplotlib来解决这个问题其实并不容易,因为标准的legend接口只支持为一张图像创建一个图例.如果我们使用legend接口再创建第二个,那么第一个图例就会被覆盖

Matplotlib中我们解决这个问题就是创建一个图例艺术家对象,然后调用底层的ax.add_artist()方法来为图片添加第二个图例
 

  1. Fig,Axes=plt.subplots(1)
  2. lines=[]
  3. style=['-','--','-.',':']
  4. x=np.linspace(start=-np.pi,stop=np.pi,num=500)
  5. for i in range(4):
  6. lines+= Axes.plot(x,np.sin(x-i*np.pi/2),style[i],color='black')
  7. Axes.axis('equal')
  8. Axes.legend(lines[:2],['Line A','Line B'],loc='uppper right',frameon=False)
  9. from matplotlib.legend import Legend
  10. Leg=Legend(Axes,lines[2:],['Line C','Line D'],loc='lower right',frameon=False)
  11. Axes.add_artist(Leg)
  12. plt.show()

参考链接:

3.Matplotlib配置图例与颜色条_鸿神的博客-CSDN博客_matplotlib添加颜色条

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号