[英]How to plot a live graph
我正在編寫一個程序來從 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()
但是有很多錯誤。
您可以嘗試以下操作:
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)
要從txt
文件中獲取ranges
:
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
開頭的每一行打印[]
內的所有文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.