赞
踩
- 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()
默认情况下图例的边框是开启的,我们可以指定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()
下面我们将以加利福尼亚州所有城市的数据(提取码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()
参考链接:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。