4

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

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()

这将绘制这个:

在此处输入图像描述

我不想要图例中的错误点和None标签,我怎样才能把它们去掉?

我在其版本 1.0.1.1190 中使用Canopy 。


编辑

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

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),))

这个输出:

情节2

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


编辑 2

原来我在该行中缺少一个逗号:

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

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

4

1 回答 1

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()

在此处输入图像描述

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

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

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()

在此处输入图像描述

于 2013-06-07T17:09:46.083 回答