温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Matplotlib绘制实时数据图表

发布时间:2021-12-02 17:35:43 来源:亿速云 阅读:227 作者:小新 栏目:大数据

小编给大家分享一下如何使用Matplotlib绘制实时数据图表,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

背景介绍

将学习如何使用Matplotlib绘制实时数据图表。我们将学习如何监控不断更新的CSV文件,并在该文件进入时绘制该CSV文件中的值。这对于绘制来自API或传感器或任何其他频繁来源的数据非常有用。让我们开始吧...

如何使用Matplotlib绘制实时数据图表

动态生成数据

接下来我们模拟一个实时数据的产生,动态的追加到data.csv文件中去,来看代码实现:

import csvimport randomimport time
x_value = 0total_1 = 1000total_2 = 1000fieldnames = ["x_value", "total_1", "total_2"]with open('data.csv', 'w') as csv_file:    csv_writer = csv.DictWriter(csv_file, \    fieldnames=fieldnames)    csv_writer.writeheader()while True:    with open('data.csv', 'a') as csv_file:        csv_writer = csv.DictWriter(csv_file,\         fieldnames=fieldnames)        info = {            "x_value": x_value,            "total_1": total_1,            "total_2": total_2        }        csv_writer.writerow(info)        print(x_value, total_1, total_2)
       x_value += 1        total_1 = total_1 + random.randint(-6, 8)        total_2 = total_2 + random.randint(-5, 6)    time.sleep(1)

绘制实时数据图表

我们来实现动态读取上边生成的data.csv文件,进行实时的绘制图表信息:

import pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimation#设置样式plt.style.use('fivethirtyeight')x_vals = []y_vals = []#定义函数读取csv文件内容def animate(i):    data = pd.read_csv('data.csv')    x = data['x_value']    y1 = data['total_1']    y2 = data['total_2']
   plt.cla()    #绘制线图    plt.plot(x, y1, label='Channel 1')    plt.plot(x, y2, label='Channel 2')    plt.legend(loc='upper left')    plt.tight_layout()#调用FuncAnimation实时调用函数每秒执行1次ani = FuncAnimation(plt.gcf(), animate, \     interval=1000)
plt.tight_layout()plt.show()

看完了这篇文章,相信你对“如何使用Matplotlib绘制实时数据图表”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI