本文展示了如何随着数据的变化动态更新Matplotlib(Python的数据可视化库)图。它提供了两种绘图方法-第一种是API(适用于大型程序或需要深度控制的程序),第二种是Pyplot接口(受Matlab启发)。在本文中,我们将展示如何在Pyplot环境中动态更新图。
使用Matplotlib Pyplot绘制线图
在创建一个动态更新的图之前,让我们首先使用Matplotlib创建/绘制一个简单的静态线图。此图稍后将升级为动态更新数据。下面是一个使用Matplotlib创建静态线图的程序。
import matplotlib.pyplot as plt
x = [1,2,3,4] # x-coordinates of the data points
y = [4,7,6,8] # y-coordinates of the data points
graph = plt.plot(x,y) # plotting the data and storing the graph in variable named graph
plt.show() # showing the resultant graph
在Matplotlib中动态更新绘图
1.使用matplotlib.animations
我们可以使用“matplotlib.animations.FuncAnimation”函数来更新绘图。
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import random
# initial data
x = [1]
y = [random.randint(1,10)]