![](/img/trans.png)
[英]Spaghetti like plot in python from a txt file with blank lines separations
[英]Python - plot from txt file, skipping lines
我的腳本有問題。 我有(blabla。)txt文件,例如:
blablaba bla
dsadsadsa
dsadsadsa
50 2323
60 2839
70 9832
80 0000
.....
....
...
和我寫的腳本:
import numpy as np
import matplotlib.pyplot as plt
with open("blabla.txt") as f:
for line in xrange(3):
next(f)
for line in f:
data = f.read()
data = data.split('\n')
x = [row.split()[0] for row in data]
y = [row.split()[1] for row in data]
index = [i for i,val in enumerate(x)]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("graph")
ax1.set_xlabel('time')
ax1.set_ylabel('distance')
ax1.set_xticklabels(x)
ax1.plot(index ,y, c='r', label='distance1')
leg = ax1.legend()
plt.locator_params(nbins=len(index)-1)
plt.show()
第一個問題是:當我想跳過(由於圖形)txt文件中的前三行時,它是真的(腳本中的語法)嗎?
第二個:在runscript之后說:
data = f.read()
ValueError: Mixing iteration and read methods would lose data.
有什么問題,是因為大小? (txt文件大約有60萬行)
感謝您的所有幫助。...Funstorm60
您可以使用:
with open("<fname>.txt", 'r') as datafile:
__data = datafile.readlines()[3:]
data = [[float(value) for value in line.split()] for line in __data]
這將為您提供2D數據數組-盡管其中不包含問題中包含的索引信息。
編輯:對不起,我錯過了對.split()
的呼叫
編輯:作為一個例子
1 2 3 4
2 3 4 5
6 5 4 3
將給出輸出:
[[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 4.0, 5.0], [6.0, 5.0, 4.0, 3.0]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.