Matplotlib实现动态更新柱状图 要在Matplotlib中实现动态更新柱状图,可以按照以下步骤进行操作 – 设置图形大小并调整子图之间和周围的间距。 创建新的图形或激活现有图形。 制作数据点和颜色列表。 使用bar()方法以data和colors,绘制柱状图。 使用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() PythonCopy