Matplotlib Dynamic Line Plot Tutorial
In matplotlib, you can create dynamic line charts using the FuncAnimation function. This function takes an update function as input and periodically calls it to update the line chart. The update function can achieve dynamic effects by modifying the data source or properties of the graph objects. Here is a basic example of how to use it:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
# 创建一个空的图形对象
fig, ax = plt.subplots()
# 定义数据源(这里使用随机数)
x_data = np.arange(0, 10, 0.1)
y_data = np.sin(x_data)
# 初始化折线图对象
line, = ax.plot(x_data, y_data)
# 更新函数,每次调用会更新折线图的数据
def update(frame):
# 修改数据源
y_data = np.sin(x_data + frame * 0.1)
# 更新折线图的数据
line.set_ydata(y_data)
return line,
# 创建动态折线图
ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)
# 显示动态折线图
plt.show()
In the above example, the update function updates the data of the line chart by modifying the values of y_data. The FuncAnimation function will periodically call the update function, each time updating the line chart and returning the updated graphic object. Finally, the dynamic line chart is displayed by calling plt.show().