[英]Issues with creating an animation using matplotlib for normal, gaussian, exponential and gamma distributions
我有以下代碼來為高斯、正態、指數和伽馬分布創建 animation:
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 軸)。
誰能告訴我哪里出錯了?
我稍微重新排列了您的代碼,以使 animation 正常工作。
animation 在animate()
function 中更新,而我使用plot_histogram()
function 來避免重復。
逐幀更新的參數是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()
使用此代碼,我得到此 animation:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.