Python 更改主情节图例标签文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23037548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change main plot legend label text
提问by N.K.
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: 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?
这就是我到目前为止所拥有的:注意蓝线的冗长标签。我希望将其标记为“音高”而不是文件名。我可以在哪条线上做到这一点?
采纳答案by CT Zhu
You need to gain access of the legend()
object and use set_text()
to change the text values, a simple example:
您需要获得legend()
对象的访问权并用于set_text()
更改文本值,一个简单的例子:
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')
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
索引L.get_texts()[0]
也适用于您的问题。
回答by Kamil Sindi
Another way:
其它的办法:
ax.legend(labels=mylabels)
回答by spatbord
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.
ksindi 的答案适用于设置标签,但正如其他一些人评论的那样,当与 seaborn 一起使用时,它可能会破坏图例颜色(在我的情况下是散点图:点和文本不再正确排列)。要解决这个问题,还要将句柄传递给 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)
(我会将此作为评论发布,但还没有足够的声誉)