python - 使用 matplotlib 针对正态分布、高斯分布、指数分布和伽马分布创建动画的问题
问题描述
我有以下代码来为高斯、正态、指数和伽玛分布创建动画:
import matplotlib.animation as animation
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
def update(curr):
if curr == n:
a.event_source.stop()
plt.cla()
plt.axis([-7,21,0,0.6])
bins = np.arange(-7,21,1)
plt.hist(x[:curr], bins=bins)
plt.gca().set_title('Sampling the' + " "+distribution+" " + 'Distribution')
plt.gca().set_ylabel('Frequency')
plt.gca().set_xlabel('Value')
plt.annotate('n = {}'.format(curr), [3,27])
n = 10000
x = np.random.normal(-2.5, 1, 10000)
distribution = 'normal'
a1 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.gamma(2, 1.5, 10000)
distribution = 'gamma'
a2 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.exponential(2, 10000)+7
distribution = 'exponential'
a3 = animation.FuncAnimation(fig, update, interval=100)
x = np.random.uniform(14,20, 10000)
distribution = 'uniform'
a4 = animation.FuncAnimation(fig, update, interval=100)
我想创建 4 个动画,一个是正态分布,一个是高斯分布,一个是指数分布,一个是伽马分布。
但是,当我运行此代码时,我得到一个空白图表(只有 y 轴和 x 轴)。
谁能告诉我哪里出错了?
解决方案
我稍微重新排列了您的代码以使动画正常工作。
动画在animate()
函数中更新,而不是我使用plot_histogram()
函数来避免重复。
逐帧更新的参数是i
,在这种情况下,它用于增加np.random._
函数从中提取的样本数。
import matplotlib.animation as animation
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2, figsize = (8, 8))
bins = np.arange(-7,21,1)
def animate(i):
normal_data = np.random.normal(-2.5, 1, 100*i)
plot_histogram(ax[0, 0], normal_data, 'Sampling the Normal Distribution', 'n = {}'.format(100*i))
gamma_data = np.random.gamma(2, 1.5, 100*i)
plot_histogram(ax[0, 1], gamma_data, 'Sampling the Gamma Distribution', 'n = {}'.format(100*i))
exponential_data = np.random.exponential(2, 100*i)+7
plot_histogram(ax[1, 0], exponential_data, 'Sampling the Exponential Distribution', 'n = {}'.format(100*i))
uniform_data = np.random.uniform(14,20, 100*i)
plot_histogram(ax[1, 1], uniform_data, 'Sampling the Uniform Distribution', 'n = {}'.format(100*i))
def plot_histogram(ax, data, title, annotation):
ax.cla()
ax.hist(data, bins = bins)
ax.set_title(title)
ax.set_ylabel('Frequency')
ax.set_xlabel('Value')
ax.annotate(annotation, [3, 27])
ani = animation.FuncAnimation(fig, animate, frames = 11, interval = 200)
plt.show()
有了这段代码,我得到了这个动画:
推荐阅读
- javascript - javascript中带有字符串的嵌套数组形成
- sublimetext3 - 突出显示匹配“引号”和“双引号”
- sql - 根据其他几列的条件计算不同的一列
- robotframework - 在robotframework中并行执行KW
- python - 在python中打印异常的正确方法是什么?
- go - 无法使用流发送块
- vue.js - 如何手动比较两条路线
- python - pandas 中的加权平均值 - 字符串索引必须是整数
- rest - 如何在 POST Query 中使用 REST API 获取作者字段值
- jmeter - JMeter将响应保存到具有自定义扩展名的文件