Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a legend with pandas and matplotlib.pyplot

This is my first attempt at plotting with python and I'm having problems creating a legend.

These are my imports:

import matplotlib.pyplot as plt
import pandas

I load my data like this:

data = pandas.read_csv( 'data/output/limits.dat', sep=r"\s+", encoding = 'utf-8' )

and plot it like this:

axdata = data.plot( label = '$|U|^{2}$' , x = 'mass', y = 'U2',
                    style = '-s', markeredgecolor = 'none' )

Apparently axdata is now an AxesSubplot.

Now I want to create a legend as described here like this:

plt.legend( (line1), ('label1') )

but I don't know how to extract a line object from an AxesSubplot

plt.legend() on its own works, but I only want some of my lines to feature in the legend. Is this the right approach? Is there another command I can use here?

EDIT:

For example, if I try:

plt.legend( [axdata], ['U2'])

I get the error:

~/.virtualenvs/science/lib/python3.3/site-packages/matplotlib/legend.py:613:
UserWarning: Legend does not support Axes(0.125,0.1;0.775x0.8)
Use proxy artist instead.

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

(str(orig_handle),))

I haven't worked out what a proxy artist is yet but I think it is a tool for when you are using a non-default graphical object, which I thought probably was not the case here because I am trying to produce a normal matlibplot plot. The words 'non-default' and 'normal' are mine - I'm not sure what they mean yet.

ANOTHER EDIT: (because I misread the comment )

plt.legend() on it's own doesn't output anything to the console but the resulting plot now has a legend auto-generated from the plotted data.

like image 782
paco_uk Avatar asked Feb 27 '14 13:02

paco_uk


1 Answers

I think what you want to do is be able to display a legend for a subset of the lines on your plot. This should do it:

df = pd.DataFrame(np.random.randn(400, 4), columns=['one', 'two', 'three', 'four'])
ax1 = df.cumsum().plot()
lines, labels = ax1.get_legend_handles_labels()
ax1.legend(lines[:2], labels[:2], loc='best')  # legend for first two lines only

Giving

enter image description here

like image 76
jmz Avatar answered Sep 16 '22 11:09

jmz