python - Python中的直方图动画
问题描述
我正在尝试使用动画制作直方图,但没有显示。
#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
函数中有一些错字:
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()
这给出了这个动画:
推荐阅读
- prometheus - Prometheus 节点导出器不会提供磁盘卷信息
- c# - ComboBox 不显示文本
- c# - 搜索完成后按钮不起作用 ASP.NET Core 3.1
- r - 错误:替换有 0 行,数据在 for 循环中有 22
- linux - 为什么“mpv $(ls video\ *)”与“mpv video\ *”不一样?(请帮助 noobie 使用 shell)
- cordova - 科尔多瓦网::ERR_INVALID_RESPONSE
- c# - Outlook 插件如何检测帐户何时被删除
- unit-testing - System.TypeLoadException:无法加载类型“Microsoft.EntityFrameworkCore.Query.Internal.IAsyncQueryProvider”
- bash - 获取 bash 中 find 命令返回的数组的最后一项
- microsoft-teams - 为组织者提供 API 以获取 Microsoft 团队会议的出席情况