本节将向大家演示在 Python 中如何运用 Matplotlib 库自定义图表中的图例。首先,我们需要在 Python 中导入所需的库与模块,并对 notebook 环境与图表风格进行初步的设置:
- import matplotlib.pyplot as plt
- plt.style.use('classic')
- %matplotlib inline
- import numpy as np
在绘图区域已经被构建完成的条件下,调用 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();
egend 函数的 loc 参数用于控制图例的位置, frameon 参数用于设置是否显示图例的边框线:
- ax.legend(loc='upper left', frameon=False)
- fig
参数 ncol 用于控制图例的列数,当参数的值为 2 时,对应图表中的图例则分为两列显示:
- ax.legend(frameon=False, loc='lower center', ncol=2)
- fig
以上内容节选自 数析学院,原文内容较多,有需要的同学可以直接查看原文


雷达卡




京公网安备 11010802022788号







