2

我正在尝试在 matplotlib 子图中同时绘制四个动画。这是数据:

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)
xs=[x1,x2,x3,x4]
bins=[np.linspace(-6,1, num=21),np.linspace(0,15, num=21),np.linspace(7,20, num=21),np.linspace(14,20, num=21)]

现在,我尝试了几种方法。这个工作得很好:

def update1(curr):
    if curr==10000:
        ani.event_source.stop()
    for ax in axs:
        ax.cla()
    axs[0].hist(xs[0][:curr], bins=bins[0], normed=True)
    axs[1].hist(xs[1][:curr], bins=bins[1], normed=True)
    axs[2].hist(xs[2][:curr], bins=bins[2], normed=True)
    axs[3].hist(xs[3][:curr], bins=bins[3], normed=True)
fig, ((ax1,ax2),(ax3,ax4))=plt.subplots(2,2, sharex=True)
axs=[ax1,ax2,ax3,ax4]
ani=animation.FuncAnimation(fig, update1,interval=50)

但奇怪的是,这个没有:

def update2(curr):
    if curr==10000:
        ani.event_source.stop()
    for i in range(len(axs)):
        axs[i].cla()
    for i in range(len(axs)):
        x=xs[i]
        axs[i].hist(x[:curr], bins=bins[i], normed=True)
fig, ((ax1,ax2),(ax3,ax4))=plt.subplots(2,2, sharex=True)
axs=[ax1,ax2,ax3,ax4]
ani=animation.FuncAnimation(fig, update2,interval=50)

这只是绘制图形和轴,但不填充直方图。我知道它在动画之外工作(我试过)。有人可以解释发生了什么吗?我看过这些:

绘制多个子图动画

子图中直方图的动画

第一个似乎是无用的,而第二个有效,但我的初始查询尚未解决。

4

1 回答 1

1

将 python3.8-devmatplotlib==3.2.2and一起使用numpy==1.19.0,您的代码对我来说效果很好。这是对我来说很好的整个脚本:

from matplotlib import numpy as np
from matplotlib import animation
from matplotlib import pyplot as plt

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)
xs=[x1,x2,x3,x4]
bins=[
    np.linspace(-6,1, num=21),
    np.linspace(0,15, num=21),
    np.linspace(7,20, num=21),
    np.linspace(14, 20, num=21)
]


def update1(curr):
    if curr==10000:
        ani.event_source.stop()
    for ax in axs:
        ax.cla()
    axs[0].hist(xs[0][:curr], bins=bins[0], normed=True)
    axs[1].hist(xs[1][:curr], bins=bins[1], normed=True)
    axs[2].hist(xs[2][:curr], bins=bins[2], normed=True)
    axs[3].hist(xs[3][:curr], bins=bins[3], normed=True)
fig, ((ax1,ax2),(ax3,ax4))=plt.subplots(2,2, sharex=True)
axs=[ax1,ax2,ax3,ax4]
ani = animation.FuncAnimation(fig, update1, interval=50)
plt.show()


def update2(curr):
    if curr==10000:
        ani.event_source.stop()
    for i in range(len(axs)):
        axs[i].cla()
    for i in range(len(axs)):
        x=xs[i]
        axs[i].hist(x[:curr], bins=bins[i], normed=True)
fig, ((ax1,ax2),(ax3,ax4))=plt.subplots(2,2, sharex=True)
axs=[ax1,ax2,ax3,ax4]
ani=animation.FuncAnimation(fig, update2,interval=50)
plt.show()

唯一真正的区别是我必须取出normed=True导致错误的部件:

AttributeError: 'Rectangle' object has no property 'normed'

我知道这不是答案,但我无法重现 OP 问题,所以我发布了一些有效的东西。

于 2020-06-29T18:36:55.063 回答