多语言展示
当前在线:627今日阅读:152今日分享:13

python如何在matplotlib中绘制图例legend?

matplotlib 是Python的可视化包与工具,可视化必然涉及到图例这一块,图例的英文乘法:legend, 用于区分不同的形状:
工具/原料

Anaconda3.exe

方法/步骤
1

首先导入使用到的包,matplotlib.pyplot, numpy:

2

接着设置图的大小,添加子图,figsize用于设置图的大小:

3

再接着,我们使用numpy创建正弦,余弦曲线的点集合,并调用plot方法绘制:

4

然后,我们只需要一行代码,plt.legend(loc='位置'), 把图例加上了:

5

但是,我们可能满足于这种显示方式,我想要把图例单独单个显示,拆分出来,这里重要的代码就是,获取到legend ,调用add_artist方法,不然会被覆盖掉,到此,legend图例的操作完成了。

6

一个好看的图例:

源码
1

# 导入matplotlib.pyplot, numpy 包import numpy as npimport matplotlib.pyplot as plt# 添加主题样式plt.style.use('mystyle')# 设置图的大小,添加子图fig = plt.figure(figsize=(5,5))ax = fig.add_subplot(111)#绘制sin, cosx = np.arange(-np.pi, np.pi, np.pi / 100)y1 = np.sin(x)y2 = np.cos(x)sin, = ax.plot(x, y1, color='red', label='sin')cos, = ax.plot(x, y2, color='blue', label='cos')ax.set_ylim([-1.2, 1.2])# 第二种方式 拆分显示sin_legend = ax.legend(handles=[sin], loc='upper right')ax.add_artist(sin_legend)ax.legend(handles=[cos], loc='lower right')plt.show()

2

import numpy as npimport matplotlib.pyplot as plt# 添加主题样式plt.style.use('mystyle')# 设置图的大小,添加子图fig = plt.figure(figsize=(5,5))ax = fig.add_subplot(111)for color in ['red', 'green']:     n = 750     x, y = np.random.rand(2, n)     scale = 200.0 * np.random.rand(n)     ax.scatter(x, y, c=color, s=scale,                 label=color, alpha=0.3,                 edgecolors='none')ax.legend() ax.grid(True)plt.show()END

推荐信息