matplotlib上的标签在循环中

时间:2013-09-02 22:24:32

标签: python matplotlib pandas

使用以下代码:

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

生成:(我在评论行中留下了我的错误代码)

Subs plot

如何获取“subsm”PER_CHG中的变量标签以显示在图例中?而不是PER_CHG(这是字段名称???) 同样我会想要加粗其中一条特定的线? (按名称或索引?)....

1 个答案:

答案 0 :(得分:1)

您可以在图中设置label个对象的Line2D属性:

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>

,并提供:

enter image description here

您可以根据您的示例进行调整:

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

ax2.legend()