Legend labels - interaction with functions

David Simpson <david.simpson@...2017...> writes:

This is probably my lack of knowledge of python, but how do I set up
legend labels for some bar-plots that have been produced inside a
function. For example, the following will nicely plot my bar-plots, but
then legend doesn't know about the colours used, so here just uses black
for both labels.

Legends for multiple histograms don't behave the way people expect,
because the colors are taken bar by bar, first from one histogram, then
from the second histogram, etc. You need to take just one bar from each
histogram and pass them as the first argument to legend:

···

------------------------------------------------------------------------
from pylab import *

x=arange(0,5)
y=array([ 1.2, 3.4, 5.4, 2.3, 1.0])
z=array([ 2.2, 0.7, 0.4, 1.3, 1.2])

def plotb(x,y,col):
         p=bar(x,y,color=col)
         return p[0]

p1 = plotb(x,y,'k')
p2 = plotb(x+0.4,z,'y')

legend((p1, p2), ('YYY','ZZZ'))
show()
------------------------------------------------------------------------

I think this behavior of legend is suboptimal, but there is a logic to
it: by default you label objects in the order you draw them, and the
histogram plot happens to consist of several similarly-colored objects.

--
Jouni K. Sepp�nen
http://www.iki.fi/jks

The best solution would be to rewrite the hist to use a collection.
This would make legend behave properly, would be a lot faster, but
would break a fair amount of legend code. Probably a good thing to do
for 0.98

JDH

···

On Thu, May 22, 2008 at 9:45 AM, Jouni K. Seppänen <jks@...397...> wrote:

I think this behavior of legend is suboptimal, but there is a logic to
it: by default you label objects in the order you draw them, and the
histogram plot happens to consist of several similarly-colored objects.