Here's an example of what I mean:
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()
which will plot this:
I don't want the error points and the None label in the legend, how can I take those out?
I'm using Canopy in its version 1.0.1.1190.
After trying Joe's solution with this code:
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()
I get this warning:
/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),))
and this output:
where the first label is not showing for some reason. Ideas?
Turns out I was missing a comma in the line:
scatt, = plt.plot(xdata, ydata, 'go--', label='Data', zorder=1)
After adding it everything worked like a charm. Thanks Joe!
On newer versions of matplotlib, what you're wanting is the default behavior. Only artists with an explicitly assigned label will appear in the legend.
However, it's easy to control what's displayed in the legend. Just pass in only the artists you'd like to label:
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()
Alternately, you could specify label='_nolegend_'
for the errorbar
plot, but I don't know what versions of matplotlib support that, and passing in explicit lists of artists and labels will work for any version.
If you'd like to add other artists:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With