【问题标题】:Labels on matplotlib within a loop循环内 matplotlib 上的标签
【发布时间】:2013-09-02 22:24:31
【问题描述】:

使用以下代码:

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

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

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

【问题讨论】:

    标签: python matplotlib pandas


    【解决方案1】:

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

    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>
    

    给予:

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

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

    【讨论】:

    • 关闭,我想我现在的问题是我不知道如何跳出我的 For 循环或将此解决方案合并到其中? (仍然是基本的python newb)
    • H9 是否会随着循环的每次迭代而改变,从而得到len(subsl) 不同的图?
    • 感谢您一直以来的出色帮助。我会在上午再摆弄一些:-)
    • 对该代码进行细微更改可以解决问题,但当然不能在这里为 subsl 中的 subsm 格式化: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.) 打印
    • FWIT set_lable 参数应该是 (subsm)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2018-10-29
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多