Matplotlib - 隐藏错误栏'标签&传奇中的点

时间:2013-06-07 17:04:00

标签: python matplotlib enthought

这是我的意思的一个例子:

import matplotlib.pyplot as plt

xdata = [5, 10, 15, 20, 25, 30, 35, 40]
ydata = [1, 3, 5, 7, 9, 11, 13, 15]
yerr_dat = 0.5

plt.figure()

plt.plot(xdata, ydata, 'go--', label='Data', zorder=1)

plt.errorbar(xdata, ydata, yerr = yerr_dat, zorder=2, fmt='ko')

plt.legend()

plt.show()

将绘制此图:

enter image description here

我不想在图例中使用错误点和标签,我该如何解决?

我在其1.0.1.1190版本中使用 Canopy


修改

使用此代码尝试Joe的解决方案后:

import matplotlib.pyplot as plt

xdata = [5, 10, 15, 20, 25, 30, 35, 40]
ydata = [1, 3, 5, 7, 9, 11, 13, 15]
yerr_dat = 0.5
value = 20

plt.figure()

scatt = plt.plot(xdata, ydata, 'go--', label='Data', zorder=1)
hline = plt.hlines(y=5, xmin=0, xmax=40)
vline = plt.vlines(x=20, ymin=0, ymax=15)

plt.errorbar(xdata, ydata, yerr = yerr_dat, zorder=2, fmt='ko')

plt.legend([scatt, vline, hline], ['Data', 'Horiz line', 'Verti line = %d' % value], fontsize=12)

plt.show()

我收到了这个警告:

/home/gabriel/Canopy/appdata/canopy-1.0.0.1160.rh5-x86/lib/python2.7/site-packages/matplotlib/legend.py:628: UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0xa09a28c>]
Use proxy artist instead.

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist

  (str(orig_handle),))

并输出:

plot2

第一个标签由于某种原因未显示。想法?


编辑2

原来我错过了一行中的逗号:

scatt, = plt.plot(xdata, ydata, 'go--', label='Data', zorder=1)

添加之后,一切都像魅力一样。谢谢乔!

1 个答案:

答案 0 :(得分:5)

在较新版本的matplotlib上,您想要的是默认行为。只有具有明确指定标签的艺术家才会出现在图例中。

但是,很容易控制图例中显示的内容。只需传递您想要标记的艺术家:

import matplotlib.pyplot as plt

xdata = [5, 10, 15, 20, 25, 30, 35, 40]
ydata = [1, 3, 5, 7, 9, 11, 13, 15]
yerr_dat = 0.5

plt.figure()

dens = plt.plot(xdata, ydata, 'go--', zorder=1)

plt.errorbar(xdata, ydata, yerr = yerr_dat, zorder=2, fmt='ko')

plt.legend(dens, ['Density Profile'])

plt.show()

enter image description here

或者,您可以为label='_nolegend_'绘图指定errorbar,但我不知道matplotlib的哪个版本支持该版本,并且传递明确的艺术家和标签列表将适用于任何版本。

如果您想添加其他艺术家:

import matplotlib.pyplot as plt

xdata = [5, 10, 15, 20, 25, 30, 35, 40]
ydata = [1, 3, 5, 7, 9, 11, 13, 15]
yerr_dat = 0.5

plt.figure()

# Note the comma! We're unpacking the tuple that `plot` returns...
dens, = plt.plot(xdata, ydata, 'go--', zorder=1)
hline = plt.axhline(5)

plt.errorbar(xdata, ydata, yerr = yerr_dat, zorder=2, fmt='ko')

plt.legend([dens, hline], ['Density Profile', 'Ceiling'], loc='upper left')

plt.show()

enter image description here