Change main plot legend label text
Asked Answered
D

4

77

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 = data[channels[0]]
data_BS_R = data[channels[1]]
data_BS_Y = data[channels[2]]
plot_BS_P = data_BS_P.plot() #data_BS_P is a pandas dataframe
axBS = plot_BS_P.gca()
axBS.plot(data_BS_R, label='Roll')
axBS.plot(data_BS_Y, label='Yaw')
axBS.set_ylabel('Amplitude (urad)')
axBS.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=3,
            fancybox=True, shadow=True)
ml1 = MultipleLocator(10)
ml2 = MultipleLocator(3600)
axBS.yaxis.set_minor_locator(ml1)
axBS.xaxis.set_minor_locator(ml2)
plot_BS_P.save('L1-SUS-BS_M1_DAMP_PRY_INMON.jpg')

And this is what I have so far: enter image description here Notice the lengthy label for the blue line. I'd like that to be labeled as "Pitch" instead of the file name. In which line can I do that?

Delaryd answered 12/4, 2014 at 23:53 Comment(3)
You haven't posted enough code to solve this problem. Post the code where the blue line is plotted. I assume the problem is in this line plot_BS_P = data_BS_P.plot().Cheesecloth
@ebarr, plot_BS_P = data_BS_P.plot() did it. data_BS_P is likely a pandas DataFrame, which has it own name blot-in. Am I right, O.P.?Bestir
It's the data_BS_P.plot() that plots the blue line. The line above this is data = TimeSeriesDict.fetch(channels, start, end, verbose=True) and the rest is the massive list of channels I have to download...Delaryd
B
104

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.

Bestir answered 13/4, 2014 at 0:7 Comment(3)
In interactive mode, add plt.gcf().canvas.draw() to redraw the figure with the new label. (In the provided example, plt.savefig updates the figure before it is saved.)Gilding
a bit shorter : L.texts[0]..set_text('shorter')Gratian
Can't get this to work with xarray.DataArray.plot.line()Excelsior
C
117

Another way:

ax.legend(labels=mylabels)
Cuellar answered 14/2, 2016 at 3:35 Comment(6)
This was by far the easiest way presented here for my use case. Thank you.Brazell
equivalently, if ax isn't explicitly defined then of course plt.legend(labels=my_labels) where my_labels is a list.Lowboy
This broke the legend patch colors when used on boxplots made with seaborn.Zobe
I used it but it does not preserve the colors I don't know why...Kathlenekathlin
how to pass a dictionary ? seems not to work, i don't how which is the order of classes...Tees
It provides the proper labels, but colors instead completely disappeared.Jeremie
B
104

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.

Bestir answered 13/4, 2014 at 0:7 Comment(3)
In interactive mode, add plt.gcf().canvas.draw() to redraw the figure with the new label. (In the provided example, plt.savefig updates the figure before it is saved.)Gilding
a bit shorter : L.texts[0]..set_text('shorter')Gratian
Can't get this to work with xarray.DataArray.plot.line()Excelsior
D
8

To avoid messing up color and marker size of the legend keys when plotting with seaborn:

handles, previous_labels = ax.get_legend_handles_labels()
ax.legend(handles=handles, labels=new_labels)
Duer answered 26/7, 2023 at 11:54 Comment(0)
L
4

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)

Lan answered 12/11, 2019 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.