我正在编写一个程序以从txt文件读取数据:
[2.8389999866485596, 2.8459999561309814, inf, 0.3540000021457672, 0.3070000112056732, 0.28700000047683716, 0.296999990940094, 0.29600000381469727]
该图没有y轴,目前这是我编写的代码:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
f = open('sample_data.txt', 'r').read()
lines = f.split('\n')
xs=[]
ys=[]
for line in lines:
if len(line) > 1:
x,y = line.split(',')
xs.append(float(x))
ys.append(float(y))
ax1.clear()
ax1.plot(xs,ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
但是有很多错误。
答案 0 :(得分:0)
您可以尝试以下方法吗?
def animate(i):
f = open('sample_data.txt', 'r').read().replace('\n', '')
ys = list(map(float, f.split(',')))
# lines = f.split('\n')
# xs=[]
# ys=[]
# for line in lines:
# if len(line) > 1:
# x,y = line.split(',')
# xs.append(float(x))
# ys.append(float(y))
ax1.clear()
ax1.plot(ys)
要从ranges
文件中获取txt
:
fp = r"python .txt"
with open(fp, 'r') as infile:
data = infile.read()
for val in data.split('\n'):
if val.startswith('ranges'):
print(list(map(lambda x: x.strip(), val.split(':')[1].strip().replace('[', '').replace(']', '').split(','))))
print()
它将从[]
开始的每一行打印ranges
内的所有文本。