作圖時圖例往往都會出現一個圖例框內,如果需要不同類型的圖例分別顯示,比如顯示兩個圖例。
基本上,出現兩個圖例的話,需要調用兩次 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)
圖例效果如下:
如果想移動圖例在圖形中的位置(比如將圖例移到數據區域的外側),請參考官方文檔。