在 Matplotlib 中动态更新条形图
pythonserver side programmingprogramming更新于 2025/8/8 17:48:17
要在 Matplotlib 中动态更新条形图,我们可以采取以下步骤 −
- 设置图形大小并调整子图之间和周围的填充。
- 创建新图形或激活现有图形。
- 列出数据点和颜色。
- 使用 bar() 方法绘制带有 数据 和 颜色 的条形图。
- 使用 FuncAnimation() 类,通过反复调用函数 animation 来制作动画,该函数设置条形图的高度和条形图的面色。
- 要显示图形,请使用 show() 方法。
示例
import numpy as np from matplotlib import animation as animation, pyplot as plt, cm plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() data = [1, 4, 3, 2, 6, 7, 3] colors = ['red', 'yellow', 'blue', 'green', 'black'] bars = plt.bar(data, data, facecolor='green', alpha=0.75) def animate(frame): global bars index = np.random.randint(1, 7) bars[frame].set_height(index) bars[frame].set_facecolor(colors[np.random.randint(0, len(colors))]) ani = animation.FuncAnimation(fig, animate, frames=len(data)) plt.show()
输出

相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

