Change main plot legend label text

前端 未结 3 665
傲寒
傲寒 2020-12-24 12:16

So far I have been able to label the subplots just fine but I\'m having an issue with the main one.

Here\'s the relevant part of my code:

data_BS_P =         


        
相关标签:
3条回答
  • 2020-12-24 12:43

    You need to gain access of the legend() object and use set_text() to change the text values, a simple example:

    plt.plot(range(10), label='Some very long label')
    plt.plot(range(1,11), label='Short label')
    L=plt.legend()
    L.get_texts()[0].set_text('make it short')
    plt.savefig('temp.png')
    

    enter image description here

    In your case, you are changing the first item in the legend, I am quite sure the 0 index in L.get_texts()[0] applies to your problem too.

    0 讨论(0)
  • 2020-12-24 12:48

    The answer by ksindi works for setting the labels, but as some others commented, it can break the legend colours when used with seaborn (in my case a scatterplot: the dots and text didn't line up properly anymore). To solve this, also pass the handles to ax.legend.

    # the legend has often numbers like '0.450000007', the following snippet turns those in '0.45'
    label_list = []
    for t in ax.get_legend_handles_labels():
        # the first result will be all handles, i.e. the dots in the legend
        # the second result will be all legend text
        label_list.append(t)
    
    new_list = []
    for txt in label_list[1]:
        if txt[0] == '0':
            txt = str(txt)[:4]
        new_list.append(txt)
    label_list[1] = new_list
    
    ax.legend(handles=label_list[0], labels=label_list[1])
    

    (I would have posted this as a comment, but don't have enough reputation yet)

    0 讨论(0)
  • 2020-12-24 13:03

    Another way:

    ax.legend(labels=mylabels)
    
    0 讨论(0)
提交回复
热议问题