Python中的直方图动画 [英] Histogram animation in Python

查看:76
本文介绍了Python中的直方图动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用动画制作直方图,但未显示.

I am trying to make a histogram using animation, but it is not showing.

#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)    

推荐答案

update 函数中存在一些错字:

You have some typo inside the update function:

  • 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])
  • plt.gca.set_ylabel('frequency') should be replaced by plt.gca().set_ylabel('frequency')
  • plt.annoate('n={}'.format(curr),[3,27]) should be replaced by 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()

给出以下动画:

这篇关于Python中的直方图动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆