How do I set label for an already plotted line in matplotlib?

混江龙づ霸主 提交于 2019-12-21 07:56:08

问题


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', ...)

Is there a way to do this in Matplotlib?


回答1:


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')

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

ax.plot(x, y, 'b.-', ...)
ax.lines[-1].set_label('line 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.


A minimal example:

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



来源:https://stackoverflow.com/questions/36624379/how-do-i-set-label-for-an-already-plotted-line-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!