【问题标题】:Histogram animation in PythonPython中的直方图动画
【发布时间】:2020-10-28 05:51:22
【问题描述】:

我正在尝试使用动画制作直方图,但没有显示。

#using animation library

%matplotlib notebook
import pandas as pd
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt

n=100

x=np.random.randn(n)


def update(curr):
    if curr==n:
        a.event_source.stop()
    plt.cla()
    bins=np.arange(-4,4,0.5)
    plt.hist(x[:curr],bins=bins)
    plt.axis([-4,4,0,30])
    plt.gca().set_title('sampling the normal distribution')
    plt.gca.set_ylabel('frequency')
    plt.gca().set_xlabel('value')
    plt.annoate('n={}'.format(curr),[3,27])
    
    
    
fig=plt.figure()
a=animation.FuncAnimation(fig,update,interval=100)    

【问题讨论】:

    标签: python python-3.x matplotlib animation histogram


    【解决方案1】:

    update 函数中有一些错字:

    • plt.gca.set_ylabel('frequency') 应替换为 plt.gca().set_ylabel('frequency')
    • plt.annoate('n={}'.format(curr),[3,27]) 应替换为 plt.gca().annotate('n={}'.format(curr),[3,27])

    检查此代码:

    %matplotlib notebook
    import pandas as pd
    import numpy as np
    import matplotlib.animation as animation
    import matplotlib.pyplot as plt
    
    n = 100
    
    x = np.random.randn(n)
    
    
    def update(curr):
        if curr == n:
            a.event_source.stop()
        plt.cla()
        bins = np.arange(-4, 4, 0.5)
        plt.hist(x[:curr], bins = bins)
        plt.axis([-4, 4, 0, 30])
        plt.gca().set_title('sampling the normal distribution')
        plt.gca().set_ylabel('frequency')
        plt.gca().set_xlabel('value')
        plt.gca().annotate('n={}'.format(curr), [3, 27])
    
    
    fig = plt.figure()
    a = animation.FuncAnimation(fig, update, interval = 100)
    
    plt.show()
    

    给出这个动画:

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 2021-11-28
      • 2021-11-27
      • 2020-07-07
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多