简介
在上一文中,我们介绍了画布和坐标轴。接下来我们继续介绍如何在坐标轴实例中加入更多的元素,比如标题、轴标、图例等。
标题
推荐使用坐标轴实例的 set_title 方法来创建标题:
1 |
>>>ax.set_title('标题') |
轴标
set_xlabel 和 set_ylabel 方法能够分别创建x轴和y轴的标签:
1 2 |
>>>ax.set_xlabel('X') >>>ax.set_ylabel('Y') |
图例
创建图例的方法有两种,一种是直接调用 legend 方法,并传入图例的值:
1 |
>>>ax.legend(['legend1', 'legend2', 'legend3']) |
但是这种方法容易出错,当改变其中的某条线时,图例不会跟着变化。因此推荐使用第二种方法,就是在绘图的时候就传入 label 参数:
1 2 3 |
>>>ax.plot(x, y, label='legend1') >>>ax.plot(x, y, label='legend2') >>>ax.legend() |
legend 方法有一个 loc 参数,可以指定图例放在图中的什么位置:
字符串 | 代号 |
---|---|
‘best’ | 0 |
‘upper right’ | 1 |
‘upper left’ | 2 |
‘lower left’ | 3 |
‘lower right’ | 4 |
‘right’ | 5 |
‘center left’ | 6 |
‘center right’ | 7 |
‘lower center’ | 8 |
‘upper center’ | 9 |
‘center’ | 10 |
可以使用字符串或者相对应的代号:
1 2 |
>>>ax.legend(loc='best') >>>ax.legend(loc=0) |
在不知道选择图例位置的情况下,建议使用 'best' 。
废话不多说,直接来做图就知道了:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
>>>import matplotlib.pyplot as plt >>>import numpy as np >>>x = np.linspace(0, 10, 5) >>>fig = plt.figure() >>>ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) >>>ax.plot(x, x ** 2, label='line1') >>>ax.plot(x, x ** 3, label='line2') >>>ax.set_title('Lines') >>>ax.set_xlabel('X') >>>ax.set_ylabel('Y') >>>ax.legend(loc='best') >>>plt.show() |
得到如下图形:
颜色
matplotlib中颜色的定义直接使用 color 参数,具体详见matplotlib颜色表。
可以使用颜色的名字或者RGB值(例如: '#1155dd' )。
1 2 3 |
>>>ax.plot(x, y, color='r') # 或 >>>ax.plot(x, y, color='#1155dd') |
线型
通过 linestyle 或者 ls 参数控制线的类型;通过 linewidth 或者 lw 参数控制线的宽度:
1 |
>>>ax.plot(x, y, ls=':', lw=1.5) |
透明度
通过 alpha 参数控制透明度,范围在(0, 1)之间:
1 |
>>>ax.plot(x, y, alpha=0.5) |
标记
通过 marker 参数改变点的标记类型,可参考matplotlib标记表(marker):
1 |
>>>ax.plot(x, y, marker='+') |
使用上面介绍的来做图:
1 2 3 4 5 6 7 8 9 10 |
>>>x = np.linspace(0, 10, 5) >>>fig = plt.figure() >>>ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) >>>ax.plot(x, x ** 2, label='line1', color='y', ls=':', lw=1.5, marker='+') >>>ax.plot(x, x ** 3, label='line2', color='g', ls='-', lw=2.0, marker='o', alpha=0.5) >>>ax.set_title('Lines') >>>ax.set_xlabel('X') >>>ax.set_ylabel('Y') >>>ax.legend(loc='best') >>>plt.show() |
得到如下图形:
总结
本文介绍了添加标题、轴标、图例的方法,并且介绍了如何改变绘图的颜色、线型、透明度、标记的方法。作为基础的第一篇,掌握这些技能已经能够完成不错的绘图操作了。在后续我们还会补充一些比较偏门的绘图操作。