我正在尝试使用 matplotlib 制作自定义图例。 example in the matplotlib documentation不适用于我的设置。这也不符合。
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
fig, ax = plt.subplots()
patch1 = mpatches.Patch(color='#a6cee3', label='Blue')
patch2 = mpatches.Patch(color='#1f78b4', label='Bluerish')
patch3 = mpatches.Patch(color='#33a02c', label='Greener')
patch4 = mpatches.Patch(color='#fdbf6f', label='Kind of orange')
patch5 = mpatches.Patch(color='#ff7f00', label='Orange')
all_handles = (patch1, patch2, patch3, patch4, patch5)
leg = ax.legend(all_handles)
ax.add_artist(leg)
plt.show()
如何让它产生所需的图例?
我使用的是 Mac OSX 10.10.3、Python 2.7.6、Matplotlib 1.3.1。
编辑:@xnx 下面的解决方案适用于 Python 3,如果使用 Matplotlib 2.1.1,则适用于 Python 2.7.11(感谢 @DavidG)。
最佳答案
您应该显式地将 handles
参数设置为 ax.legend
:
leg = ax.legend(handles=all_handles)
我认为您的代码的问题在于,legend
的第一个(位置)参数被视为您希望标记的对象序列,但您没有任何对象。
关于macos - 在 matplotlib Python2 中生成自定义图例(并且仅是图例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444816/