macos - 在 matplotlib Python2 中生成自定义图例(并且仅是图例)

标签 macos python-2.7 matplotlib

我正在尝试使用 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 的第一个(位置)参数被视为您希望标记的对象序列,但您没有任何对象。

enter image description here

关于macos - 在 matplotlib Python2 中生成自定义图例(并且仅是图例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444816/

相关文章:

macos - Mac OS X 下的 Windows Mobile 开发

c++ - 一秒计时器

c++ - mac os X 上的 qmake 子目录模板

c++ - Monodevelop 中是否支持 C++ 的代码折叠?

python - 使用 subprocess.Popen() 或 subprocess.check_call() 时程序卡住

Python:Matplotlib imshow shift xlabel 数字

Python 正则表达式 : how to do a negative lookahead with a string which don't start immediately?

python - 延迟加载/配置要继承的类

python - 如何通过matplotlib删除plot_wireframe中的隐藏线?

python - 如何在 pyplot 上保存 rgba 图像?