legend()的一个用法:
当我们有多个 axes时,我们如何把它们的图例放在一起呢??
我们可以这么做:
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 设置中文字体为微软雅黑
# 定义房价
price = [10000, 12000, 16000, 14000, 13000, 19000]
# 定义成交量
total = [100, 50, 40, 60, 120, 40]
# 定义年份
year = [2010, 2011, 2012, 2013, 2014, 2015]
fig, ax = plt.subplots(1, 1)
# 共享x轴,生成次坐标轴
ax_sub = ax.twinx()
# 绘图
l1, = ax.plot(year, price, 'r-', label='price') #注意这里是关键,l1后面多了一个',',这样才可以显示多个对象的图例
l2, = ax_sub.plot(year, total, 'g-', label='total')
# 放置图例
plt.legend(handles=[l1, l2], labels=['price', 'total'], loc=0)
# 设置主次y轴的title
ax.set_ylabel('房价(元)')
ax_sub.set_ylabel('成交量(套)')
# 设置x轴title
ax.set_xlabel('年份')
# 设置图片title
ax.set_title('主次坐标轴演示图')
plt.show()
在legend的参数中, loc参数设置图例的显示位置的:
best | 0 |
---|---|
upper right | 1 |
upper left | 2 |
lower right | 4 |
lower left | 3 |
right | 5 |
center left | 6 |
center right | 7 |
lower center | 8 |
upper center | 9 |
center | 10 |