![](/img/trans.png)
[英]Creating an Array from a text file with more than one data type in Python
[英]plot data from more than one text file using python
我有兩個文件。 Xdata.txt
和Ydata.txt
。 每行Xdata
應繪制出的每一行Ydata
。 關鍵是每行中的列數不同。 例如:
Xdata.txt :
row1: 1 2 3 4 5 6
row2: 1 2 3 4
Ydata.txt :
row1: 1 2 3 4 5 6
row2: 1 2 3 4
我想繪制
Xdata[row1], Ydata[row1]
Xdata=[row2], Ydata[row2]
在一個數字。 請幫助我解決這種情況。
您可以通過將每個文件加載到列表中來啟動該過程。
with open("Xdata.txt", "r") as xf:
x_list = xf.readlines()
with open("Ydata.txt", "r") as yf:
y_list = yf.readlines()
然后,您使用 python 的zip
函數來抓取每對線並繪制它們。 這會將 Xdata.txt 中的第 1 行與 Ydata.txt 中的第 1 行配對,依此類推:
for (x_line, y_line) in zip(x_list, y_list):
# Split out the data from the line, which is stored as a string
x_data = x_line.split(' ')
y_data = y_line.split(' ')
# Insert data conversion from string to numbers if needed
# Modify plotting code as needed
plot(x_data, y_data)
試試這個(@jrmylow 答案的實現):
輸入:
Xdata.txt
1 4 3 6 5 6
1 2 3 7
Ydata.txt
1 2 3 4 5 6
1 2 3 4
import matplotlib.pyplot as plt
with open("Xdata.txt", "r") as xf:
x_list = xf.readlines()
with open("Ydata.txt", "r") as yf:
y_list = yf.readlines()
for (x_line, y_line) in zip(x_list, y_list):
x_data = x_line.split(' ')
y_data = y_line.split(' ')
plt.plot(x_data, y_data)
plt.legend(['first','second'])
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.