如何将matplotlib的动画用于标准图和条形图的组合?

时间:2018-06-24 19:39:02

标签: python numpy matplotlib

我想制作一个2D随机行走的动画,以及一个随着步数的更新而更新的直方图。但是我只能更新显示助步器的图,直方图仅显示空白的直方图。

这是我的代码:

import numpy as np
from scipy.stats import norm
from scipy.stats import uniform
import matplotlib.pyplot as plt
from matplotlib import animation

def brownian_motion( n ):

    # uniformly distributed angles
    angle = uniform.rvs( size=n, loc=.0, scale=2.*np.pi )

    # normal distributed step size
    r = norm.rvs( size=n )

    # x and y coordinates (position added to previous coordinate --> cumulative sum)
    x = np.cumsum( r * np.cos(angle) )
    y = np.cumsum( r * np.sin(angle) )

    return np.array( (x, y, r, angle) )

# generate array with coordinates of a walker doing brownian motion
random_walk = brownian_motion( 500 )

# prepare histogram for step sizes
bins_set        = np.linspace( np.min(random_walk[2,:]), np.max(random_walk[2,:]), 20+1 )
hist, bin_edges = np.histogram( random_walk[2,:], bins=bins_set )
bin_width       = (bin_edges[-1] - bin_edges[0])/len(bin_edges)

# initialize figure with 2 subplots
fig = plt.figure( figsize=(14,6) )
ax1 = fig.add_subplot( 1,2,1 )  # 2D position of walker
ax2 = fig.add_subplot( 1,2,2 )  # histogram of step sizes

# initialize line object and bar plot
line1,       = ax1.plot( [], [] )
barContainer = ax2.bar( bin_edges[:-1], hist, width=bin_width )

# set axes ranges for 2D plot displaying position of walker
ax1.set_xlim( np.min(random_walk[0,:]), np.max(random_walk[0,:]) )
ax1.set_ylim( np.min(random_walk[1,:]), np.max(random_walk[1,:]) )

def animate(frame_number):

    # update 2D plot displaying position of walker
    line1.set_data( random_walk[0,0:frame_number], random_walk[1,0:frame_number] )

    # update histogram
    hist_tmp, bin_edges_tmp = np.histogram( random_walk[2,0:frame_number], bins=bins_set )
    for i, bar in enumerate(barContainer):
        bar.set_height( hist_tmp[i] )

    return line1,

anim = animation.FuncAnimation( fig, animate,
                                frames=500,
                                blit=True, repeat=False
                               )

plt.show()

因此,据我所知,问题在于barContainer并未真正包含在动画处理过程中,我也需要将其返回。但是我不知道该怎么做。

因此,我的问题是如何使用matplotlib的animate 组合标准图和条形图?

0 个答案:

没有答案