[Tutor] Help with Matplotlib labels

Sean Carolan scarolan at gmail.com
Mon Jun 18 23:52:13 CEST 2012


I'm working on a simple python web app that generates graphs, because
managers love graphs.  I've got it about 90% done, but I'm having
trouble getting labels onto my stacked graph.  In the matplotlib
documentation there is a nice example showing how to create the
legend.  Note how the variables p1 and p2 are used to generate the
legend in this example:

http://matplotlib.sourceforge.net/examples/pylab_examples/bar_stacked.html

<code>
p1 = plt.bar(ind, menMeans,   width, color='r', yerr=womenStd)
p2 = plt.bar(ind, womenMeans, width, color='y',
             bottom=menMeans, yerr=menStd)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind+width/2., ('G1', 'G2', 'G3', 'G4', 'G5') )
plt.yticks(np.arange(0,81,10))
plt.legend( (p1[0], p2[0]), ('Men', 'Women') )
</code>


Unfortunately my graph is generated dynamically. How can I create my
legend when my 'bar' objects have no names to refer to?

    for admin in bd:
        bar(ind, bd[admin], width, color=colordict[admin])
    xticks(ind+width/2., datenames)
    legend()
    grid('on')
    outfile = 'testfile.png'
    savefig('/var/www/'+outfile)
    return outfile


More information about the Tutor mailing list