matplotlib:条形图动画只能工作一次

我已经使用FuncAnimation的方法实现了一个动画matplotlib.animation。


代码没有错误,但我不知道问题到底出在哪里!


代码:


def visualization(self):

    fig = plt.figure()

    

    def animation_frame(i):

        print(i)

        trimmed_dist = self.get_distributions(i, self.window_size + i)

        # create labels             

        label_no = len(trimmed_dist)

        labels = []

        for index in range(label_no):

            from_ = index * self.bucket_length

            to_ = (index + 1) * self.bucket_length

            label = '{:.2f} - {:.2f}'.format(from_, to_)

            labels.append(label)

        

        #create bar chart

        colors = plt.cm.Dark2(range(label_no))

        plt.xticks(rotation=90)

        plt.bar(x=labels, height=trimmed_dist, color=colors)

        

    frames_no = len(self.percentages) - self.window_size

    print('frames_no:', frames_no)

    animation = FuncAnimation(fig, animation_frame, frames=frames_no, interval=1000)

    return animation

输出:

http://img3.mukewang.com/644783eb0001fd5205530353.jpg

PS 1:值为frame_no877。

PS 2:我认为问题在于可视化方法中的返回。所以我已经更改了代码,但它仍然无法正常工作。


慕姐8265434
浏览 65回答 1
1回答

明月笑刀无情

我相信您正在 Jupyter 笔记本中运行您的代码。%matplotlib notebook在这种情况下,您应该在代码的开头添加。中找到的代码,以查看它是否适合您。编辑我在笔记本中实现了你的部分代码。由于我不知道self.percentages、self.window_size和是什么self.get_distributions以及self.bucket_length它们有哪些值,为了简单起见,我设置了labels = ['a', 'b', 'c']和trimmed_dist = [3*i, 2*i, i**2],以便运行一个简单的动画。这是我的代码:%matplotlib notebookfrom matplotlib.animation import FuncAnimationimport matplotlib.pyplot as pltdef animation_frame(i):    plt.gca().cla()        labels = ['a', 'b', 'c']    trimmed_dist = [3*i, 2*i, i**2]    label_no = len(trimmed_dist)        colors = plt.cm.Dark2(range(label_no))    plt.xticks(rotation=90)    plt.bar(x=labels, height=trimmed_dist, color=colors)    plt.title(f'i = {i}') # this replaces print(i)    plt.ylim([0, 100])    # only for clarity purposefig = plt.figure()frames_no = 877print('frames_no:', frames_no)animation = FuncAnimation(fig, animation_frame, frames=frames_no, interval=1000)这就是结果。我添加plt.gca().cla()是为了在每次迭代时擦除前一帧。print(i)声明对我也不起作用,所以我将其替换plt.title(f'i = {i}')为 order 以便写i在标题中。相反,print('frames_no:', frames_no)工作正常。如您所见,我的动画运行了,所以请尝试实现我对您的代码所做的更改。如果动画仍然不运行,请尝试检查self.percentages、self.window_size和self.get_distributions的self.bucket_length值和类型,以确保正确计算labels和。trimmed_dist
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python