我有一个具有以下结构的数据文件:
cat data.dat
% 1
0.9 0.9 0.6 0.5
0.0 0.1 0.3 0.2
0.5 0.2 0.0 0.1
% 2
0.2 0.6 0.2 0.3
0.2 0.1 0.1 0.2
0.4 0.2 0.1 0.1
我只是展示了一个简单的例子,只有 2 组数据,但文件
比这个大得多。我想要的是读取文件
Python,然后告诉 Python 计算以 % 2
开头的集合
如下。从这个集合中,我想绘制 row=1 w.r.t.这
在本例中,整数数组为 1,2,3,4。
我可以用 GNUPLOT 来做到这一点,但我花了很多时间,因为首先我需要 剪切我想要的集合并将其粘贴到临时文件中。其次,我使用AWK 转置矩阵。
我想知道我的建议在 Python 中是否可行。
谢谢。
最佳答案
好吧,如果您需要从文件中访问各种数据(考虑 @gboffi post ,则有一个限制,即设置标签按连续顺序排列):
from matplotlib import pyplot as plt
data = []
with open('cat_data.dat') as f:
for line in f:
if line[1].isalpha():
continue
if line.startswith('%'):
data.append([])
continue
data[-1].append([float(x) for x in line.split()])
# Now you have all values in data:
# [[[0.9, 0.9, 0.6, 0.5], [0.0, 0.1, 0.3, 0.2], [0.5, 0.2, 0.0, 0.1]], [[0.2, 0.6, 0.2, 0.3], [0.2, 0.1, 0.1, 0.2], [0.4, 0.2, 0.1, 0.1]]]
_set = 2
row = 1 # Corresponds to 0.2 0.1 0.1 0.2
plt.plot(range(1, 5), data[_set - 1][row])
plt.show()
关于python - 如何用Python绘制结构化数据文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37416026/