Bar plots and legends in pylab/matplotlib

13 June, 2009 - 09:41

I like working with Matplotlib aka Pylab for my plotting needs in Python, but today I stumbled on a weird issue when creating a mixed bar + line plot with legend. Take the following snippet:

pylab.bar(x, yr, color='#88aa33', align='center', label='histogram')
pylab.plot(x, yc, 'bo-', label='cumulative')
pylab.legend()

This generates something like (note the entry overload in the legend):

Legend entry overload.

[Update: this issue seems to be solved. The issue described here occurred with Matplotlib version 0.91.2. With Matplotlib 0.99.0 I don't have this problem anymore.]

Apparently, the pylab.bar() call creates and returns a list of separate rectangles, instead of some compound "bar plot" object. The pylab.legend() call treats these rectangles separately and adds an entry to the legend for each one of them.

The workaround is to instruct pylab.legend() more precisely how to handle the plotted data series. The trick is to get the results of pylab.bar() and pylab.plot() and pass them as follows to pylab.legend()

bars = pylab.bar(x, yr, color='#88aa33', align='center')
line = pylab.plot(x, yc, 'bo-')
pylab.legend((bars[0], line), ('histogram', 'cumulative'))

Note how I only pass the first item from the bars list on the last line

The result now looks like:

omg!!1 this legend rulez the kittenxz.

For more info, see the Matplotlib documentation on pylab.legend().

24 November, 2010 - 11:24

Nice work

Studer (not verified)

Nice work.
By the way, I'm really interested in doing the same graph, can you send me the code you used ?

11 March, 2010 - 19:22

Thanks!

Alan LaMielle (not verified)

Thanks for the tip, I'm creating some plots for my thesis and needed to create a legend for a multi-bar comparison plot. This led me to what I needed!

Post new comment

The content of this field is kept private and will not be shown publicly.
  • No HTML tags allowed
  • Lines and paragraphs break automatically.

More information about formatting options