【问题标题】:Add a legend for an animation (of Artists) in matplotlib在 matplotlib 中为(艺术家的)动画添加图例
【发布时间】:2016-12-16 19:31:37
【问题描述】:

我用这样的一组图像制作了一个动画(10 张快照):

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import time

infile = open ('out.txt')

frame_counter = 0

N_p = 100
N_step = 10
N_line = N_p*N_step

for s in xrange(N_step):
        x, y = [], []
        for i in xrange(N_p):
                data = infile.readline()
                raw = data.split()
                x.append(float(raw[0]))
                y.append(float(raw[1]))

        xnp = np.array(x)
        ynp = np.array(y)

        fig = plt.figure(0)
        ax = fig.add_subplot(111, aspect='equal')
        for x, y in zip(xnp, ynp):

                cir = Circle(xy = (x, y), radius = 1)
                cir.set_facecolor('red')
                ax.add_artist(cir)
                cir.set_clip_box(ax.bbox)

                ax.set_xlim(-10, 150)
                ax.set_ylim(-10, 150)
        fig.savefig("step.%04d.png" % frame_counter)
        ax.remove()
        frame_counter +=1

现在我想为每个显示时间步长的图像添加一个图例。 为此,我必须为这 10 个图像中的每一个设置图例。问题是我测试了不同的东西,比如 ax.set_labelcir.set_label ,... 我得到这样的错误:

 UserWarning: No labelled objects found. Use label='...' kwarg on individual plots

根据这个错误,我必须为我的个人情节添加标签,但由于这是艺术家的情节,我不知道我该怎么做。

【问题讨论】:

  • 当只显示一种类型的点时,为什么还需要一个图例?
  • 我想在动画中显示时间。
  • 让我细化一下:当动画中只显示一种点时,为什么还需要一个图例来显示时间?
  • 我正在自学matplotlib,在每个试验情节中我想添加不同的东西,以便以后可以使用这些示例文件。我只是在jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial中找到一个我喜欢做的例子,摆锤动画
  • 无论如何,如果下面的答案解决了问题,你应该accept它,如果没有,你应该完善你的问题。

标签: python matplotlib


【解决方案1】:

如果出于某种原因您需要legend,您可以将您的 Circle 显示为句柄并使用一些文本作为标签。

ax.legend(handles=[cir], labels=["{}".format(frame_counter)])

如果您真的不需要图例,您可以使用一些 text 来放置在轴内。

ax.text(.8,.8, "{}".format(frame_counter), transform=ax.transAxes)

【讨论】:

    猜你喜欢
    • 2012-07-10
    • 2021-05-14
    • 2015-01-26
    • 1970-01-01
    • 2019-11-24
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多