【发布时间】:2021-12-01 07:55:00
【问题描述】:
我正在尝试对我使用 GridSpec 设置的 4 个子图进行动画处理,并且我想在其中表示我用随机数设置的 4 个分布,我在其中设置子图、分布和动画函数的代码是以下:
import matplotlib
import matplotlib.animation as animation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Create the figure and set the grid:
fig = plt.figure()
gspec = matplotlib.gridspec.GridSpec(6,6)
top_left = plt.subplot(gspec[0:2,0:3])
top_right = plt.subplot(gspec[0:2,3:], sharey = top_left)
bottom_left = plt.subplot(gspec[3:5,0:3], sharey = top_left)
bottom_right = plt.subplot(gspec[3:5,3:], sharey = top_left)
#Create the random variables:
x1 = np.random.normal(-2.5, 1, 10000)
x2 = np.random.gamma(2, 1.5, 10000)
x3 = np.random.exponential(2, 10000)+7
x4 = np.random.uniform(14,20, 10000)
#Create the function:
n = 10000-100
def anim(curr, subplot = None, dist = None):
if curr >= 100:
if curr == n+100:
a.event_source.stop()
subplot.cla()
bins = np.arange(p1,p2,step)
subplot.hist(dist[:curr], bins = bins)
subplot.gca().set_ylabel('Frequency')
subplot.gca().set_xlabel('Value')
subplot.annotate('n={}'.format(curr+100))
#Create the necessary lists for looping:
subplots = [top_left, top_right, bottom_left, bottom_right]
bins = [np.arange(-6,2,0.5),np.arange(-1,15,0.5), np.arange(5,20,0.5), np.arange(13.5,20.5,0.5)]
dists = [x2,x2,x3,x4]
然后,我尝试使用 animation.FuncAnimation 函数进行循环:
for i in range(3):
a = animation.FuncAnimation(fig, anim(subplot = subplots[i], dist = dists[i]))
但我收到以下错误:
----------------------------------- ---------------------------- TypeError Traceback(最近一次调用 最后)在() 2 3 for i in range(3): ----> 4 a = animation.FuncAnimation(fig, anim(subplot = subplots[i], dist = dists[i]))
TypeError: anim() 缺少 1 个必需的位置参数:'curr'
为什么要我指定curr?我认为FuncAnimation 函数能够自己理解这是循环的参数。我想我不太了解animation 模块的功能
注意:我不得不说我尝试了与这个类似的代码,但只是针对一个单一的情节,没有任何网格,也没有循环。在这种情况下,我不必在 anim 函数中指定 subplot 或 dist 参数,因为在定义 anim 函数时没有必要包含它们,因为我只需要传递一个情节我只是在函数中指定这些值,在这种情况下,我没有收到任何错误,但现在我必须指定更多参数,我得到了它。
【问题讨论】:
标签: python matplotlib animation