欢迎访问宙启技术站
智能推送

通过Python实现动态更新柱状图

发布时间:2023-12-27 19:45:53

通过Python实现动态更新柱状图可以使用matplotlib库来实现。下面是一个例子,具体实现步骤如下:

首先,我们需要导入matplotlib和numpy库,分别用于绘图和生成数据。

import matplotlib.pyplot as plt
import numpy as np

然后,我们定义一个函数来更新柱状图的数据。在这个例子中,我们随机生成一个包含5个元素的数组,表示柱状图的5个柱子的高度。

def update_bar_chart():
    heights = np.random.randint(1, 10, size=5)
    bar_chart.set_height(heights)
    plt.draw()

接下来,我们创建一个柱状图对象,并定义初始的柱子高度和标签。这里使用了numpy库的arange函数来生成[0, 1, 2, 3, 4]的数组作为x轴标签。

x_labels = np.arange(5)
initial_heights = np.zeros(5)
bar_chart = plt.bar(x_labels, initial_heights)
plt.xticks(x_labels, x_labels)

最后,我们设置动态更新图表的定时器,并将更新柱状图的函数作为回调函数。

timer = plt.gcf().canvas.new_timer(interval=1000)
timer.add_callback(update_bar_chart)
timer.start()

在最后,我们调用show函数展示柱状图。

plt.show()

完整的代码如下:

import matplotlib.pyplot as plt
import numpy as np

def update_bar_chart():
    heights = np.random.randint(1, 10, size=5)
    bar_chart.set_height(heights)
    plt.draw()

x_labels = np.arange(5)
initial_heights = np.zeros(5)
bar_chart = plt.bar(x_labels, initial_heights)
plt.xticks(x_labels, x_labels)

timer = plt.gcf().canvas.new_timer(interval=1000)
timer.add_callback(update_bar_chart)
timer.start()

plt.show()

运行这段代码,就可以动态更新柱状图了。每秒钟,柱子的高度将会更新为一个随机数。这个例子中只有5个柱子,但你可以根据需要修改数组的长度来增加或减少柱子的数量。

希望这个例子可以帮助你实现动态更新柱状图。祝你成功!