【问题标题】:matplotlib: bar-plot animation only works oncematplotlib:条形图动画只能工作一次
【发布时间】:2020-11-24 22:40:35
【问题描述】:

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

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

代码:

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

输出:

PS 1:frame_no 的值为 877。

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

【问题讨论】:

标签: python matplotlib animation jupyter-notebook


【解决方案1】:

我相信您正在 Jupyter 笔记本中运行您的代码。在这种情况下,您应该在代码的开头添加%matplotlib notebook
作为参考,请尝试运行您可以在 this answer 中找到的代码,以查看它是否适合您。


编辑

我在笔记本中实现了您的部分代码。由于我不知道self.percentagesself.window_sizeself.get_distributionsself.bucket_length 是什么以及它们具有哪些值,所以为了简单起见,我设置了labels = ['a', 'b', 'c']trimmed_dist = [3*i, 2*i, i**2],以便运行简单的动画。
这是我的代码:

%matplotlib notebook
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt

def 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 purpose

fig = plt.figure()
frames_no = 877
print('frames_no:', frames_no)
animation = FuncAnimation(fig, animation_frame, frames=frames_no, interval=1000)

this 就是结果。

我添加了plt.gca().cla(),以便在每次迭代时擦除前一帧。
print(i) 语句对我也不起作用,因此我将其替换为plt.title(f'i = {i}'),以便将i 写入标题。相反,print('frames_no:', frames_no) 工作正常。

如您所见,我的动画运行了,因此请尝试实施我对您的代码所做的更改。
如果动画仍然没有运行,请尝试检查self.percentagesself.window_sizeself.get_distributionsself.bucket_length 的值和类型,以确保正确计算labelstrimmed_dist

【讨论】:

    猜你喜欢
    • 2016-11-10
    • 2017-09-10
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多