0

I'm using pylab.plot() in a for loop, and for some reason the legend has 6 entries, even though the for loop is only executed 3 times

#Plot maximum confidence                                                      
pylab.figure()
    for numPeers in sorted(peers.keys()):
        percentUni, maxes = peers[numPeers]
        labels = list(set([i[1] for i in sorted(maxes,
                                                key=itemgetter(1))]))
        percentUni = [i[0] for i in sorted(maxes, key=itemgetter(1))]

        x = []
        y = []
        ci = []
        for l in xrange(len(labels)):
            x.append(l+1)
            y.append(max(maxes[l*3:l*3+3]))                
        pylab.plot(x, y, marker='o', label = "N=%d"%numPeers)

    pylab.title('Maximal confidence in sender')
    pylab.xlabel('Contribute Interval')
    pylab.ylabel('Percent confident')
    pylab.ylim([0,1])
    pylab.xlim([0.5, 7.5])
    pylab.xticks(xrange(1,8), labels)
    pylab.legend(loc='upper right')

The plot looks like this, with each legend entry having exactly 2 copies.

stupid plot

I know the loop only runs 3x, because if I put in a print statement to debug, it only prints the string 3x.

I did see this in my search, but didn't find it helpful: Duplicate items in legend in matplotlib?

Community
  • 1
  • 1
CAJ
  • 297
  • 1
  • 3
  • 12

2 Answers2

0

I had a similar problem. What I ended up doing is add plt.close() at the beginning of my loop. I suspect you're seeing 6 because you have a nested loop where you're changing the x and y.

Community
  • 1
  • 1
mauve
  • 2,707
  • 1
  • 20
  • 34
  • I am changing the x and the y, but they are obliterated and rebuilt during each iteration. Anyway, I tried your suggestion and added a pylab.close() right after the for. It didn't work: http://i.imgur.com/bpatcP6.png – CAJ Jul 09 '14 at 19:52
  • I believe the equivalent would be pylab.plot.close() – mauve Jul 09 '14 at 19:53
0

It ended up being a bug/type on my part, where I was supposed to write

maxes = [i[0] for i in sorted(maxes, key=itemgetter(1))]

instead of

percentUni = [i[0] for i in sorted(maxes, key=itemgetter(1))]

This mistake meant that maxes remained a list of 2-tuples instead of a list of integers, which is why things were plotted twice. And because I restricted the y-axis, I never saw that there were additional data elements plotted.

Thanks for your help, those who did answer!

CAJ
  • 297
  • 1
  • 3
  • 12