在Matplotlib中动态更新绘图的3种方法

本文展示了如何随着数据的变化动态更新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)]

你可以使用以下代码来实现动态更新图表: ```python import time import matplotlib.pyplot as plt import numpy as np from numpy.random import rand if __name__ == &#39;__main__&#39;: # 启用交互模式 plt.ion() # 创建一个图形和一组子图 figure, ax = plt.subplots() # 使用lines保存绘图对象 lines, = ax.plot([], []) ax.set_autoscaley_on(True) ax.grid() for n in range(600): # 生成数据 xdata = np.arange(128) ydata = rand(128) # 更新数据 lines.set_xdata(xdata) lines.set_ydata(ydata) # 重新缩放 ax.relim() ax.autoscale_view() # 绘制并刷新图形 figure.canvas.draw() figure.canvas.flush_events() time.sleep(0.01) ``` 这段代码使用matplotlib库实现了动态绘图的功能。首先启用交互模式,并创建一个图形对象和子图对象。然后,通过循环生成随机数据,并更新图表数据。最后,绘制并刷新图形,以实现动态更新图表的效果。你可以根据需要调整数据生成和更新的逻辑,以满足你的需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [matplotlib 动态刷新绘图(最简单的方法)](https://blog.csdn.net/falwat/article/details/123306390)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [jupyter notebook 实现matplotlib动态刷新](https://download.csdn.net/download/weixin_38644141/14910441)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

python收藏家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值