Python实现条形图动态变化
时间: 2024-04-12 08:25:55 浏览: 15
Python可以使用matplotlib库来实现条形图的动态变化。下面是一个简单的示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 创建初始数据
x = np.arange(5)
y = np.array([10, 15, 7, 12, 9])
# 创建条形图
fig, ax = plt.subplots()
bars = ax.bar(x, y)
# 更新数据函数
def update_data():
# 生成新的数据
new_y = np.random.randint(1, 20, size=5)
# 更新条形图的高度
for bar, h in zip(bars, new_y):
bar.set_height(h)
# 动态更新函数
def animate(i):
update_data()
return bars
# 设置动画
anim = plt.animation.FuncAnimation(fig, animate, frames=10, interval=500)
# 显示动画
plt.show()
```
这段代码使用了matplotlib的animation模块来实现动态更新。首先,我们创建了一个初始的条形图,然后定义了一个`update_data`函数来生成新的数据,并通过循环更新每个条形的高度。接下来,我们定义了一个`animate`函数,它会在每一帧中调用`update_data`函数来更新数据,并返回更新后的条形图对象。最后,我们使用`FuncAnimation`函数创建动画,并通过`plt.show()`显示动画。