以下是一个示例代码,演示了如何不断重绘具有更新数据的路径:
import matplotlib.pyplot as plt
# 初始化数据
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
# 创建绘图对象和子图
fig, ax = plt.subplots()
# 创建初始线条对象
line, = ax.plot(x, y)
# 更新数据和重新绘制函数
def update_data():
# 更新数据
x.append(x[-1] + 1)
y.append((x[-1])**2)
# 重新设置线条数据
line.set_data(x, y)
# 重新设置坐标轴范围
ax.relim()
ax.autoscale_view()
# 重新绘制图形
plt.draw()
# 不断重绘的循环
while True:
# 更新数据和重新绘制
update_data()
# 暂停一段时间,以便观察更新效果
plt.pause(0.5)
这个示例代码使用matplotlib.pyplot
库创建了一个简单的折线图。在每次循环中,通过调用update_data()
函数,更新了数据并重新绘制了图形。plt.pause()
函数用于在每次重绘后暂停一段时间,以便观察更新效果。这样就可以实现不断重绘具有更新数据的路径的效果。