1

using the following code:

for subsm in subsl:
    H9,ax2,subsm = perchg2(st, subsm)
    ax2=H9.plot() 
    ax2.set_title('Percent change All Subdivisions (rolling 4q avg)')
#    ax2.plot([],label=[subsm])
    ax2.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
#    ax2.plot([1], label='test2')   
    print

Which generates: (I left my bad code in the comment lines)

Subs plot

How do I get the "subsm" The varible label in PER_CHG to display in the legend? instead of the PER_CHG (which is the field name???) Similarly I will want to Bold one of the specific lines?? (by name or index?)....

1 Answer 1

2

You can set the label property of Line2D objects in the plot:

In [40]: import pandas.util.testing as tm

In [41]: df = DataFrame(randn(10, 5))

In [42]: df
Out[42]:
       0      1      2      3      4
0 -1.225  0.144 -0.539  0.765 -0.269
1 -0.261  0.830 -0.008  2.096  1.123
2 -0.887 -1.272 -0.232  0.926  0.760
3 -0.241 -1.617 -0.360  0.333 -1.676
4  0.845 -1.661  1.405  1.444 -0.064
5 -2.013 -0.906 -1.854 -0.951 -1.117
6 -1.442 -0.400 -0.455  1.163  0.688
7 -0.960  1.451 -0.106 -0.244  0.091
8  0.525  1.551 -0.644 -1.248 -1.080
9 -1.252 -1.085  0.795 -0.310 -0.072

In [43]: ax = df.plot(legend=False)                                                                       

In [44]: lines = ax.get_lines()

In [45]: for line in lines:
   ....:     line.set_label(tm.rands(10))
   ....:

In [46]: legend()
Out[46]: <matplotlib.legend.Legend at 0x8c946d0>

giving:

enter image description here

You can adapt this to your example:

# do this outside of the first loop
lines = ax2.get_lines()
for line, subsm in zip(lines, subsl):
    line.set_label(subsm)

ax2.legend()
Sign up to request clarification or add additional context in comments.

5 Comments

Close, I guess my issue now is that I don't know how to either break out of my For loop or incorporate this solution into it?? (still basic python newb)
Does H9 change with each iteration of the loop, so that you get len(subsl) different plots?
Thanks for your continued, excellent help. I'll fiddle some more in the am :-)
minor change this code does the trick but of course can't format it here for subsm in subsl: H9,ax2,subsm = perchg2(st, subsm) ax2=H9.plot() ax2.set_title('Percent change All Subdivisions (rolling 4q avg)') lines = ax2.get_lines() for line, subsm in zip(lines, subsl): line.set_label(subsm) ax2.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) print
FWIT the set_lable argument should be (subsm)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.