将实时生成的数据用matplotlib画动态曲线,并将数据写入csv文件中

背景:
最近有个需求,需要将数据画成折线图便于观察,并且数据是实时生成的(与时间有关),数据数量不确定,在网上看到大多数都是基于固定数据来进行画图,很少有将动态生成的数据画成图形的,因此研究了一下。

实现思路:

  1. 使用库:画图用matplotlib实现
  2. 获取跟随时间变化的数据,并将时间作为x轴,数据作为y轴
  3. 写一个循环,将数据“动态刷新”在画板上
  4. 由于数据数量不确定,因此x轴显示的数量个数最好固定(不然数据太多挤在一堆不好看),例如显示20个数据,当总数据个数超过20个后,将第一个数据不显示(将列表中的第一个值删除),最后一位新增一个数据,整体呈现的效果就是整个图像在向x轴的负方向移动。

方法实现不难,详情请见下列代码:

import matplotlib.pylab as plt
import time
import numpy as np
import random
from matplotlib.pyplot import MultipleLocator
import csv

x_list = []     # 用于存放x轴数据
y_list = []     # 用于存放y轴数据
temp_list_x = []    # 临时存放x轴数据
temp_list_y = []    # 临时存放y轴数据
show_num = 10   # x轴显示的数据个数,例:show_num = 10表示x轴只显示10个数据
num = 0

plt.ion(
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是符合要求的Python代码: ```python import re import csv import pandas as pd import matplotlib.pyplot as plt import argparse import os # 定义命令行参数 parser = argparse.ArgumentParser(description='Convert txt files in current directory to csv and generate trend chart.') parser.add_argument('-t', '--title', nargs='+', help='Specify the titles of columns in CSV file.') parser.add_argument('-c', '--chart', action='store_true', help='Generate trend chart.') args = parser.parse_args() # 获得当前文件夹下所有txt文件文件名 txt_files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.txt')] for txt_file in txt_files: # 读取txt文件内容 with open(txt_file, 'r') as f: content = f.read() # 提取txt文件的数字数据 data = re.findall(r'\d+', content) # 将数据转换为二维矩阵 num_cols = len(args.title) num_rows = int(len(data) / num_cols) matrix = [[0] * num_cols for i in range(num_rows)] for i in range(num_rows): for j in range(num_cols): matrix[i][j] = data[i * num_cols + j] # 将数据写入CSV文件 csv_file_name = os.path.splitext(txt_file)[0] + '.csv' with open(csv_file_name, 'w', newline='') as f: writer = csv.writer(f) writer.writerow(args.title) for row in matrix: writer.writerow(row) # 生成曲线趋势图 if args.chart: df = pd.read_csv(csv_file_name, index_col=0) for col in df.columns: plt.plot(df.index, df[col], label=col) plt.legend() plt.xlabel('Index') plt.ylabel('Value') plt.title('Trend Chart of {}'.format(os.path.splitext(txt_file)[0])) plt.show() ``` 这个代码使用了re、csv、pandas、matplotlib和argparse这些库。它通过命令行参数来指定CSV文件的标题,并在需要时生成曲线趋势图。代码假设CSV文件的第一列为行标题,第一行为列标题。如果需要更改,请修改代码。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值