Matplotlib,带有一个标签的多个不同标记的图例

Cra*_*Arm 9 python matplotlib

以下是情况的简化情节:

情节例子

我希望能够为一组不同的标记设置一个标签,而不是让每个数据点标记都有一个单独的标记.我希望能有一个像这样的传奇:

<triangle> <square> <hexagon> <diamond> <circle> Shotcrete strength data points
<green line> 10 minute strength
<blue line> 60 minute strength
<yellow line> 1 day strength
<orange line> 7 day strength
<red line> 28 day strength
Run Code Online (Sandbox Code Playgroud)

我想这样做是因为在最终的情节中我会有三组数据点并显示18(3组*6点/组)标记/标签组合将是混乱的.

我在Python 2.7中使用Matplotlib.

Hoo*_*ked 3

注意:此答案保留作为正确答案的指南 - 但它并不能解决所述问题。请参阅下面的编辑,了解 matplotlib 不支持 Patch 集合的问题。


如果您想要完全自定义,解决此问题的一种方法是使用所谓的代理艺术家:

from pylab import *

p1 = Rectangle((0, 0), 1, 1, fc="r")
p2 = Circle((0, 0), fc="b")
p3 = plot([10,20],'g--')
legend([p1,p2,p3], ["Red Rectangle","Blue Circle","Green-dash"])

show()
Run Code Online (Sandbox Code Playgroud)

在这里,您可以准确指定您希望图例的外观,甚至可以使用非标准绘图形状(补丁)。

编辑:这种方法有一些困难,matplotlib 仅支持图例中的这些艺术家而不进行调整。对于 matplotlib v1.0 及更早版本,支持的艺术家如下。

Line2D
Patch
LineCollection
RegularPolyCollection
CircleCollection
Run Code Online (Sandbox Code Playgroud)

您对多个分散点的请求将通过Patch Collection来完成,这在上面不受支持。理论上,对于 v1.1,这是可能的,但我不知道如何实现。

  • 我目前正在使用伪线来制作我的传奇。我想我也许可以使用这样的东西(http://matplotlib.sourceforge.net/users/legend_guide.html#legend-handler):`code` z = np.random.randn(10) p1a, = plt .plot(z, "ro", ms=10, mfc="r", mew=2, mec="r") # 红色实心圆圈 p1b, = plt.plot(z[:5], "w+", ms=10, mec="w", mew=2) # 白十字 plt.legend([p1a, (p1a, p1b)], ["Attr A", "Attr A+B"]) `code` 组合将多个标记放在一行上。 (2认同)