Python通过曲线图实时显示数据、并把数据保存到txt文件

本文介绍如何使用Python的Matplotlib库实现实时更新的曲线图,并将数据同步到txt文件,以列形式存储。展示了从数组创建曲线图,到文件操作和数据持久化的完整过程。

1.Python通过曲线图实时显示数据

代码:

import matplotlib.pyplot as plt

x = []               # 定义数组x
y = []               # 定义数组y
plt.ion()             # 开启interactive mode 成功的关键函数
plt.figure(figsize=(8,6))  # 定义曲线图的大小


for i in range(10):
    x.append(i)       # 将i的值写入x数组
    y.append(i*i)     # 将i*i的值写入x数组
    plt.clf()         # 清除图的内容
    plt.plot(x,y)     # 绘制x、y数组的数据
    plt.pause(0.1)   # 暂停0.01s
    plt.ioff()        # 关闭

f = open(r'C:\Users\hdy\Desktop\python\write_read_txt\imagenames.txt',"r+")
f.truncate()             # 清除txt文件里面的内容
f.write('\n' + str(x))   # 往txt文件写入x数组数据(按列写入)
f.write('\n' + str(y))   # 往txt文件写入y数组数据(按列写入)

r.close()

曲线图效果:
在这里插入图片描述
txt文件效果:
在这里插入图片描述

2.X数组数据和Y数组数据在txt文件中按列方向一一对应

import matplotlib.pyplot as plt
import time

x = []               # 定义数组x
y = []               # 定义数组y
plt.ion()             # 开启interactive mode 成功的关键函数
plt.figure(figsize=(8,6))  # 定义曲线图的大小

for i in range(10):
   x.append(i)       # 将i的值写入x数组
   y.append(i*i)     # 将i*i的值写入x数组
   plt.clf()         # 清除图的内容
   plt.plot(x,y)     # 绘制x、y数组的数据
   plt.pause(0.1)   # 暂停0.01s
   plt.ioff()        # 关闭

##########################数据写入#####################################
f = open(r'C:\Users\hdy\Desktop\python\write_read_txt\imagenames.txt',"r+")
f.truncate()      # 清除txt文件里面的内容
f.write('时间' + '  ' + '金钱' + '\n')      # x,y数据列表标题
for i in range(len(x)):
   f.write('  ' + str(x[i]) + '       ' + str(y[i]) + '\n')   # 往txt文件写入x数组数据(按列写入)
f.close()

##########################数据读取打印##################################
time.sleep(0.5)
r = open(r'C:\Users\hdy\Desktop\python\write_read_txt\imagenames.txt',"r")
read = r.read()
print(read)
r.close()

txt文件内部效果:
在这里插入图片描述

同理三列、四列数据也是一样的方法。

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值