【Matplotlib】图例分开显示

作图时图例往往都会出现一个图例框内,如果需要不同类型的图例分别显示,比如显示两个图例。

基本上,出现两个图例的话,需要调用两次 legend 。第一次调用,你需要将图例保存到一个变量中,然后保存下来。第二次调用清除之前创建的第一个的图例,之后你可以通过 Axes.add_artist 函数手动将第一个图例重新添加回来。

以下为一个简单的例子进行说明:

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np

x = np.random.uniform(-1, 1, 4)
y = np.random.uniform(-1, 1, 4)

p1, = plt.plot([1,2,3])
p2, = plt.plot([3,2,1])
l1 = plt.legend([p2, p1], ["line 2", "line 1"], loc='upper left')

p3 = plt.scatter(x[0:2], y[0:2], marker = 'D', color='r')
p4 = plt.scatter(x[2:], y[2:], marker = 'D', color='g')

# This removes l1 from the axes.
plt.legend([p3, p4], ['label', 'label1'], loc='lower right', scatterpoints=1)
# Add l1 as a separate artist to the axes
plt.gca().add_artist(l1)

图例效果如下:

如果想移动图例在图形中的位置(比如将图例移到数据区域的外侧),请参考官方文档

posted @ 2016-07-18 20:16  Chris*Chen  阅读(5637)  评论(0编辑  收藏  举报