Matplotlib图例指南基本示例

时间:2015-06-11 21:55:23

标签: python matplotlib

我试图更好地理解如何使用legend(),特别是如何使用代理艺术家。我发现Legend guide严重缺乏。这篇文章有点类似于this one

我在Windows 7上使用Python 2.7.5,matplotlib 1.2.1版。我编写了这段代码,它基本上是图例指南中示例的组合:

import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')

blue_line = mlines.Line2D([], [], color='blue', marker='*',
                      markersize=15, label='Blue stars')
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend([red_patch,blue_line])

plt.show()

http://i.stack.imgur.com/E9jkA.jpg

图例标签颜色不是手柄中指定的颜色,也不是贴片和带星星的线条。我已经尝试删除和添加行,添加和删除行后的逗号等。它们是否更适合使用legend()?使用代理艺术家的任何其他提示?我不明白为什么这些例子给我的结果完全不同......

2 个答案:

答案 0 :(得分:3)

传奇指南was rewritten与matplotlib 1.4.0或更新版本兼容。您的matplotlib(1.2.1)版本已超过两年。如果文档中显示的所有内容都不能与旧版本一起使用,请不要感到惊讶。

如果您升级版本,请使用

engine_cmd

(如Legend Guide所示)而不是

ipcluster_config.py

产量

enter image description here

答案 1 :(得分:0)

我还在使用matplotlib 1.2.1所以我会告诉你什么对我有用。我发现如果我将线对象传递给legend(),我还必须单独传递标签。 [这也与le​​gened()]上的matplotlib文档一致。我稍微修改了你的例子来做这件事,它似乎有效:

import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')

blue_line = mlines.Line2D([], [], color='blue', marker='*',
                  markersize=15, label='Blue stars')
red_patch = mpatches.Patch(color='red', label='The red data')

lines = [blue_line, red_patch]
labels = [line.get_label() for line in lines]
plt.legend(lines, labels)

plt.show()

code output