配置图例¶
在可视化图形中使用图例,同时为图形元素分配不同标签。前面已有一些例子,现在我们中细节处探讨图例的绘制。
In [37]:
Copied!
import matplotlib.pyplot as plt
plt.style.use('seaborn-v0_8-whitegrid')
plt.rcParams['font.sans-serif'] =['SimHei'] #设置字体为SimHei
plt.rcParams['axes.unicode_minus'] = False #负号显式正常
import matplotlib.pyplot as plt
plt.style.use('seaborn-v0_8-whitegrid')
plt.rcParams['font.sans-serif'] =['SimHei'] #设置字体为SimHei
plt.rcParams['axes.unicode_minus'] = False #负号显式正常
In [39]:
Copied!
%matplotlib inline
import numpy as np
%matplotlib inline
import numpy as np
In [41]:
Copied!
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();
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();
如果我们希望对图例设计进行个性化,则需要对各种参数比较熟悉。
In [44]:
Copied!
ax.legend(loc='upper left', frameon=False)
fig
ax.legend(loc='upper left', frameon=False)
fig
Out[44]:
也可以使用 ncol 命令来设置图例的标签的列数。
In [47]:
Copied!
ax.legend(frameon=False, loc='lower center', ncol=2)
fig
ax.legend(frameon=False, loc='lower center', ncol=2)
fig
Out[47]:
当然,还可以定制一个图例的圆角边框 (使用fancybox) ,或者添加阴影,改变外框透明程度 (framealpha 值) 等等,
In [50]:
Copied!
ax.legend(fancybox=True, framealpha=0.9, shadow=True, borderpad=1)
fig
ax.legend(fancybox=True, framealpha=0.9, shadow=True, borderpad=1)
fig
Out[50]:
选择图例的显示元素¶
默认情况下,使用图例会显示所有标记的图形要素。如果我们只希望显示部分图形要素的图例,可以通过 plt.plot() 绘制多条图形,返回线条实例列表。这样有两种方法显示部分线条图例。一是将需要显示的线条传入plt.legend()中;第二种方法是只为需要显示的列表设置标签即可。
In [53]:
Copied!
#第一种方法
y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
lines = plt.plot(x, y)
# 读入需要显示的图形列表
plt.legend(lines[:2], ['first', 'second']);
#第一种方法
y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
lines = plt.plot(x, y)
# 读入需要显示的图形列表
plt.legend(lines[:2], ['first', 'second']);
在实践中第一种方法更为清晰直接。在默认情况下,有标签的线条图例才会显示,只需要为显示的线条设定标签即可。
In [56]:
Copied!
#第二种方法
plt.plot(x, y[:, 0], label='first')
plt.plot(x, y[:, 1], label='second')
plt.plot(x, y[:, 2:])
plt.legend(framealpha=1, frameon=True);
#第二种方法
plt.plot(x, y[:, 0], label='first')
plt.plot(x, y[:, 1], label='second')
plt.plot(x, y[:, 2:])
plt.legend(framealpha=1, frameon=True);
图例中显示不同尺寸的点¶
很多时候,默认的图例不能够满足我们的需求,如当你使用不同大小的点表示不同特征,也希望创建图例来说明,就需要针对性进行设置了。在下面的例子中,我们使用美国加州不同城市的人口数量,如果希望通过不同尺寸点来表示不同的人口规模,就可以通过一些隐藏的标签来实现。
In [59]:
Copied!
import pandas as pd
cities = pd.read_csv('data/california_cities.csv')
# Extract the data we're interested in
lat, lon = cities['latd'], cities['longd']
population, area = cities['population_total'], cities['area_total_km2']
# Scatter the points, using size and color but no label
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('经度')
plt.ylabel('纬度')
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='城市区域')
plt.title('加州城市: 区域与人口');
import pandas as pd
cities = pd.read_csv('data/california_cities.csv')
# Extract the data we're interested in
lat, lon = cities['latd'], cities['longd']
population, area = cities['population_total'], cities['area_total_km2']
# Scatter the points, using size and color but no label
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('经度')
plt.ylabel('纬度')
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='城市区域')
plt.title('加州城市: 区域与人口');
图例是图形中对象的参照,因此,如果我们希望显示何种图形,就需要先行画出来。但在本例中,我们想要的对象(灰色圆圈)并不在图形中,因此我们使用空列表将其画出来,由于图例不显示未作标签的点,因此创建了该类型图例。
需要说明,在地理信息数据处理时候,如果可以将州边界的图形显示出来,效果会更逼真。我们可以使用Matplotlib中的Basemap(底图)插件工具箱来实现。这部分内容我们会在地图绘制部分介绍。