栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

使用可视化扩展库matplotlib的模块中的legend_matplotlib中legend?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用可视化扩展库matplotlib的模块中的legend_matplotlib中legend?

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

参考链接:

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

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/783553.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号