Matplotlib学习笔记——配置图例

配置图例

简单的图例
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
import numpy as np

x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label='Sine')
ax.plot(x, np.cos(x), '--r', label='Cosine')
ax.axis('equal')
leg = ax.legend();

这里写图片描述

简单的配置
#取消图例的外边框
ax.legend(loc='upper left', frameon=False)

这里写图片描述

#用ncol参数设置图例的标签列数
ax.legend(frameon=False, loc='lower center', ncol=2)

这里写图片描述

#为图例定义圆角外框、增加阴影、改变外边框透明度(framealpha值),或者改变文字的间距
ax.legend(fancybox=True, framealpha=0.5, shadow=True, borderpad=1)

这里写图片描述

图例的高级操作

选择图例显示的元素

图例会默认显示所有元素的标签,如果你不想显示全部,可以通过一些图形命令来指定显示图例中那些元素和标签

y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
lines = plt.plot(x, y)

#lines变量是一组plt.Line2D实例
plt.legend(lines[:2], ['first', 'second']);

这里写图片描述

在图例中显示不同尺寸的点
import pandas as pd
cities = pd.read_csv('data/california_cities.csv')
#提取感兴趣的数据
lat, lon = cities['latd'], cities['longd']
population, area = cities['population_total'], cities['area_total_km2']

#用不同尺寸和颜色的散点图表示数据,但是不带标签
plt.scatter(lon, lat, label=None, c=np.log10(population), 
            cmap='viridis', s=area, linewidth=0, alpha=0.5)
plt.axis(aspect='equal')
plt.xlabel('longtidude')
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');

这里写图片描述

由于图例通常是图形中形象的参照,因此如果我们想显示某种形状,就需要将它画出来。但是在这个示例中,我们想要的对象(灰色圆圈)并不在图形中,因此把它们用空列表假装画出来。还要注意的是,图例只会显示带标签的元素。

猜你喜欢

转载自blog.csdn.net/jasonzhoujx/article/details/81773530