且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python动画中添加图例/标签

更新时间:2023-10-24 10:45:10

我根本不是 matplotlib 的专家,但在

I'm no expert on matplotlib at all, but in the Double Pendulum animation they display texts which changes, and this leads to some variations which can help you.

要获得具有实际线条颜色的图例,可以将初始设置 lines 更改为:

To get legends with the actual color of the lines, you can either change the initial setting lines to:

lines = [plt.plot([], [], label = 'line {}'.format(i))[0] for i in range(N)]

或在 init()函数中的 for 循环中添加 line.set_label().这两个似乎都按预期工作.至少在 plt.show()之前添加 plt.legend(loc =左上"").

or add a line.set_label() to the for loop in the init() function. Both these seem to work as expected. At least if you add plt.legend(loc="upper left") right before plt.show().

但是 set_label animate()函数中不起作用,但是根据链接的动画,您可以使用添加到动画中的特定文本字段,并且似乎工作得很好.在初始化后添加以下代码:

However the set_label doesn't work within the animate() function, but according to the linked animation you can use specific text fields added to the animation, and that seems to work nicely. Add the following code after initialisation of lines:

texts = [ax.text(0.80, 0.95-i*0.05,  '', transform=ax.transAxes) for i in range(N)]

并将 animate()更改为:

def animate(i):
    for j in range(N):
        lines[j].set_data([0, 2], [10*j,i]) #, label="hei {}".format(i))
        texts[j].set_text('line %d, stage %d'%(j,i))
    return lines

这会将文本放置在靠近右上角的位置,并针对每个动画步骤进行更新.由于线条仍显示其图例,因此您可以简化为仅显示舞台的一个文本.但我将消息的微调留给您自行决定.

This places the text close to the upper right corner, and is updated for each animation step. Since the lines still have their legend displayed, you possibly simplify into one text only displaying the stage. But I leave the fine tuning of messages to your discretion.

可能的另一种选择是扩展 lines.Line2D 并在动画中使用这些线条,类似于

Another alternative could possibly be to extend lines.Line2D and use these lines in your animation, something similar to this article. Not sure if this would work with animation, but if you can't get the above to work, this might be worth a try.