如何在matplotlib中为已经绘制的线设置标签? [英] How do I set label for an already plotted line in matplotlib?

查看:71
本文介绍了如何在matplotlib中为已经绘制的线设置标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中我已经执行了

In my code I've already executed

ax.plot(x, y, 'b.-', ...)

并且需要能够在事后设置相应行的标签,以具有与我想要的效果相同的效果

and need to be able to set the label for the corresponding line after the fact, to have the same effect as if I'd

ax.plot(x, y, 'b.-', label='lbl', ...)

在Matplotlib中有没有办法做到这一点?

Is there a way to do this in Matplotlib?

推荐答案

如果在创建line2D对象时抓住了它,则可以使用line.set_label()设置标签:

If you grab the line2D object when you create it, you can set the label using line.set_label():

line, = ax.plot(x, y, 'b.-', ...)
line.set_label('line 1')

如果没有,您可以从Axes中找到line2D:

If you don't, you can find the line2D from the Axes:

ax.plot(x, y, 'b.-', ...)
ax.lines[-1].set_label('line 1')

请注意,ax.lines[-1]将访问最后创建的行,因此,如果您要复制多行,则需要注意使用此方法设置标签的那一行.

Note, ax.lines[-1] will access the last line created, so if you make more than one line, you would need to be careful which line you set the label on using this method.

一个最小的例子:

import matplotlib.pyplot as plt
fig,ax = plt.subplots(1)
l,=ax.plot(range(5))
l.set_label('line 1')
ax.legend()
plt.show()

这篇关于如何在matplotlib中为已经绘制的线设置标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆