Python中的直方图动画实现教程

198 阅读2分钟

嘿,伙计们!今天,我们要进行编程,以便使用Python编程语言获得动画直方图。

Python和Matplotlib可以用来创建静态的2D图。但是Matplotlib有一个秘密的力量,也可以用来创建动态的自动更新的动画图

让我们开始吧!


1.导入模块

我们首先导入所有必要的模块/库,其中包括numpy 来创建数据。 [matplotlib](https://www.askpython.com/python-modules/matplotlib/python-matplotlib)来绘制直方图,最后matplotlib.animation 来绘制动画图。

我们还将导入HTML函数,以便将视频转换为HTML形式。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
plt.style.use('seaborn')


2.创建一个数据集

为了创建数据,我们将需要numpy模块,首先固定一个随机状态,以便使用它。接下来,我们使用linespace函数初始化bin的数量。

接下来,我们将使用linspace函数创建随机的1000个数据点。最后一步是使用直方图函数将数据点转换为直方图数据点。

np.random.seed(19680801)
HIST_BINS = np.linspace(-4, 4, 100)
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)


3.直方图的动画化

为了使直方图动画化,我们需要一个animate 函数,该函数将生成一些随机数,并持续更新各分仓的高度。

def prepare_animation(bar_container):
    
    def animate(frame_number):
        data = np.random.randn(1000)
        n, _ = np.histogram(data, HIST_BINS)
        
        for count, rect in zip(n, bar_container.patches):
            rect.set_height(count)
        
        return bar_container.patches
    
    return animate


3.显示动画直方图

hist() 函数的帮助下,我们可以得到一个BarContainer (矩形实例集合)的实例。

然后,我们将调用prepare_animation ,该函数下定义有animate

最后,我们将使用to_html5_video 函数将绘图转换为HTML格式。

fig, ax = plt.subplots()
_, _, bar_container = ax.hist(data, HIST_BINS, lw=1,ec="red", fc="blue", alpha=0.5)
ax.set_ylim(top=55)
ani = animation.FuncAnimation(fig, prepare_animation(bar_container), 50,repeat=True, blit=True)
HTML(ani.to_html5_video())


在Python中显示动画柱状图的完整实现

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
plt.style.use('seaborn')

np.random.seed(19680804)
HIST_BINS = np.linspace(-4, 4, 100)
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)

def prepare_animation(bar_container):
    
    def animate(frame_number):
        data = np.random.randn(1000)
        n, _ = np.histogram(data, HIST_BINS)
        
        for count, rect in zip(n, bar_container.patches):
            rect.set_height(count)
        
        return bar_container.patches
    
    return animate

fig, ax = plt.subplots()
_, _, bar_container = ax.hist(data, HIST_BINS, lw=1,ec="blue", fc="yellow", alpha=0.5)
ax.set_ylim(top=100)
ani = animation.FuncAnimation(fig, prepare_animation(bar_container), 50,repeat=True, blit=True)
HTML(ani.to_html5_video())


总结

我希望你在观看动画直方图时感到很有趣!你可以用不同的数据来尝试。你可以尝试用不同的数据、不同的仓位数,甚至改变直方图的速度。

编码愉快!😊