Matplotlib配置图例legend()设置透明和并排显示
2023-02-18 16:37:15 时间
1.多排显示
x=np.linspace(start=-np.pi,stop=np.pi,num=300)
plt.style.use('classic')
Fig,Axes=plt.subplots(1)
Axes.plot(x,np.sin(x),'-b',label='Sine')
Axes.plot(x,np.cos(x),'--r',label='Cosine')
Axes.axis('equal')
Axes.legend(loc='lower center',frameon=False,ncol=2)
plt.show()
2.指定frameon参数来设定边框
默认情况下图例的边框是开启的,我们可以指定frameon参数来取消边框
x=np.linspace(start=-np.pi,stop=np.pi,num=300)
plt.style.use('classic')
Fig,Axes=plt.subplots(1)
Axes.plot(x,np.sin(x),'-b',label='Sine')
Axes.plot(x,np.cos(x),'--r',label='Cosine')
Axes.axis('equal')
Axes.legend(loc='lower center',frameon=False)
plt.show()
3.在图例中显示不同尺寸的点
下面我们将以加利福尼亚州所有城市的数据(提取码666)为例来绘图,最终效果是将绘制出各个城市的位置,同时以城市面积大小来使用不同大小的圆表示
cities=pd.read_csv('california_cities.csv')
latitude,longitude=cities['latd'],cities['longd']
population,area=cities['population_total'],cities['area_total_km2']
plt.scatter(latitude,longitude,label=None,c=np.log10(population),cmap='viridis',s=area,linewidths=0,alpha=0.5)
plt.axis(aspect='euqal')a
plt.xlabel('Logitude')
plt.ylabel('Latitude')
plt.colorbar(label='log_{10}$(population)')
plt.clim(3,7)
for area in [100,300,500]:
plt.scatter([],[],c='k',alpha=0.3,s=area,label=str(area)+' km$^2$')
plt.legend(scatterpoints=1,frameon=False,labelspacing=1,title='City Area')
plt.title('California Cities : Area and Population')
plt.show()
La=1
for color in list('cmyk'):
plt.scatter([],[],c=color,s=100,label=La)
La+=1
plt.legend(frameon=False)
plt.show()
同时显示多个图例
有的时候,由于排版问题,我们可能需要在同一张图像上显示多个图例.但是用Matplotlib来解决这个问题其实并不容易,因为标准的legend接口只支持为一张图像创建一个图例.如果我们使用legend接口再创建第二个,那么第一个图例就会被覆盖
Matplotlib中我们解决这个问题就是创建一个图例艺术家对象,然后调用底层的ax.add_artist()方法来为图片添加第二个图例
Fig,Axes=plt.subplots(1)
lines=[]
style=['-','--','-.',':']
x=np.linspace(start=-np.pi,stop=np.pi,num=500)
for i in range(4):
lines+= Axes.plot(x,np.sin(x-i*np.pi/2),style[i],color='black')
Axes.axis('equal')
Axes.legend(lines[:2],['Line A','Line B'],loc='uppper right',frameon=False)
from matplotlib.legend import Legend
Leg=Legend(Axes,lines[2:],['Line C','Line D'],loc='lower right',frameon=False)
Axes.add_artist(Leg)
plt.show()
参考链接:
相关文章
- Java设计模式之建造者模式
- typecho设置伪静态_Win_IIS环境如何安装
- Java设计模式之原型模式
- VLAN间路由配置方法,单臂路由、三层交换_路由交换基础
- UltraISO软碟通老牌的ISO编辑软件V9.76
- HDLC与PPP协议原理与配置_路由交换基础内容
- cc攻击脚本详细教程,看一眼就学会
- Java设计模式之工厂模式
- PPPoE客户端原理与配置_路由交换基础
- Java设计模式之类图的六大关系
- NAT网络地址转换_路由交换基础
- UML类图的基本操作
- IDEA快捷键汇总
- Windows10推送了V21H2正式版更新_19044.1766
- NxShell_1.6.0_最新便携版和安装版下载
- Centos7上部署三台tomcat
- 访问控制列表ACL配置规则_路由交换
- Nginx
- Java设计模式之模板模式
- Java设计模式之命令模式