如何使用带有matplotlib的增量可视化同时对多个直方图进行动画处理?

时间:2019-04-01 04:06:13

标签: matplotlib animation

我正在尝试同时对多个直方图进行动画处理。该动画旨在以增量方式可视化遵循四个不同分布(正态,伽玛,指数和均匀)的样本。

我已阅读并能够使用以下线程Animate multiple shapes in python3 using matplotlib对具有多个子图的matplotlib动画文档的示例进行迭代。但是,在“更新”功能之前确定随机变量并尝试用动画逐步更新直方图会导致出现我似乎无法解决的问题。 Matplotlib版本:3.0.2

为单个直方图设置动画的代码(有效)

import matplotlib.animation as animation
import numpy as np

n = 100
x = np.random.normal(loc=2.5, scale=1.0, size=n)

fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=True, sharey=True)

def update(curr):
    if curr == n:
        a.event_source.stop()
    plt.cla()
    bins = np.arange(-2, 5, 0.5)
    ax1.hist(x[:curr], bins=bins)
    plt.axis([-2, 6, 0, 30])
    ax1.set_title('Sampling the Normal Distribution')
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value')
    plt.annotate('n = {}'.format(curr), [3,27]) 

a = animation.FuncAnimation(fig, update, interval=100)
plt.show()

我尝试对多个子图进行动画处理(没有产生预期的结果)

n = 100

x1 = np.random.normal(loc=2.5, scale=1.0, size=n)
x2 = np.random.gamma(shape=2.0, scale=1.0, size=n)
x3 = np.random.exponential(scale=1.0, size=n)
x4 = np.random.uniform(low=0, high = 5, size=n)

data = [x1, x2, x3, x4]
dist = ['Normal', 'Gamma', 'Exponential', 'Uniform']
bins = np.arange(-2,6,0.5) # generate range for bins

# plot the histograms
fig, (ax1,ax2,ax3,ax4) = plt.subplots(4, 1, sharex=True, sharey=True)

def update(curr):
    if curr == n:
        a.event_source.stop()
    plt.cla()
    ax1.hist(x1[:curr], normed=True, bins=bins, color='blue')
    ax2.hist(x2[:curr], normed=True, bins=bins, color='red')
    ax3.hist(x3[:curr], normed=True, bins=bins, color='green')
    ax4.hist(x4[:curr], normed=True, bins=bins, color='gray')

a = animation.FuncAnimation(fig, update, interval=100)

plt.show()

产生预期最终结果图的代码(无动画)

n = 100

x1 = np.random.normal(loc=2.5, scale=1.0, size=n)
x2 = np.random.gamma(shape=2.0, scale=1.0, size=n)
x3 = np.random.exponential(scale=1.0, size=n)
x4 = np.random.uniform(low=0, high = 5, size=n)

data = [x1, x2, x3, x4]
dist = ['Normal', 'Gamma', 'Exponential', 'Uniform']
bins = np.arange(-2,6,0.5) # generate range for bins

# plot the histograms
fig, (ax1,ax2,ax3,ax4) = plt.subplots(4, 1, sharex=True, sharey=True)

ax1.hist(x1, normed=True, bins=bins, color='blue')
ax2.hist(x2, normed=True, bins=bins, color='red')
ax3.hist(x3, normed=True, bins=bins, color='green')
ax4.hist(x4, normed=True, bins=bins, color='gray')

plt.show()

多个子图的预期结果(无动画)

enter image description here

多个子图的实际结果(带有动画)

enter image description here

0 个答案:

没有答案