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

[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:

For more info, see the Matplotlib documentation on pylab.legend().
Nice work
Nice work.
By the way, I'm really interested in doing the same graph, can you send me the code you used ?
Thanks!
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