1

I have a plot with 6 different subplots. I iterate through a loop to make each of the subplots and I want to add the legend for each subplot at this time too. So here is an easy example:

matrixSol = scipy.random.random((6,6,4))
print matrixSol
mylegend = ['10 Million','15 Million','1 Million','20 Million','25 Million','5 Million']

for k in range(6):
    print k
    xs = matrixSol[k,:,0]
    ys = matrixSol[k,:,1]
    zs = matrixSol[k,:,3]
    plt.subplot(2,3,k+1)
    plt.plot(ys, zs,'o', c=color[k], markersize=10)#marker = styles[k])
    #print mylegend[k]
    plt.legend((mylegend[k]),loc=2)
    plt.xlabel('X')
    plt.ylabel('Y (%)')
plt.show()

The problem is that I am getting a legend that picks only the first symbol of each member of the list, please see figure attached. What is wrong with my code???? it is such a simple thing! thank you very much! any help will be appreciated!enter image description here

2 Answers 2

5

Use:

plt.plot(ys, zs,'o', c=color[k], label=mylegend[k], markersize=10)
plt.legend(loc=2)

enter image description here

alternatively, the solution already indicated by Chris Redford also works:

plt.legend((mylegend[k],), loc=2)
0
2

I'm pretty sure it's treating the code (mylegend[k]) in the line:

plt.legend((mylegend[k]),loc=2)

As if the string (e.g. '10 Million') is itself a list (e.g. ['1', '0', ' ', 'M', 'i', 'l', 'l', 'i', 'o', 'n']).

If you change that line to use (mylegend[k],) (comma to specify it is a tuple), it might work right:

plt.legend((mylegend[k],),loc=2)
2
  • Thanks for testing it and coming back to +1. I +1ed yours as well for its completeness (ie you tested your solution). Aug 25, 2011 at 18:53
  • 1
    thank you very much Chris, I tried many things but wouldn't have thought of putting a comma there! this works!
    – Laura
    Aug 25, 2011 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.