本文介绍了在matplotlib中为(艺术家的)动画添加图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从一组这样的图像中制作了动画(10张快照):

I have made an animation from a set of images like this (10 snapshots):

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_label cir.set_label ,...我得到这样的错误:

Now I want to add a legend to each image showing the time step.For doing this I must set legends to each of these 10 images. The problem is that I have tested different things like ax.set_label , cir.set_label, ...and I get errors like this:

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

根据此错误,我必须在个人图上添加标签,但是由于这是艺术家图,所以我不知道该怎么做.

According to this error I must add label to my individual plots, but since this is a plot of Artists, I don't know how I can do this.

推荐答案

如果您出于任何原因需要 legend,您可以将您的圈子显示为句柄并使用一些文本作为标签.

If for whatever reason you need a legend, you can show your Circle as the handle and use some text as the label.

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

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

If you don't really need a legend, you can just use some text to place inside the axes.

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

这篇关于在matplotlib中为(艺术家的)动画添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:52