我有一个文本文件,格式为:
时间,秒数AreaA,cm˛AreaA,A˛AreaB,cm˛AreaB,A˛PiA,mN / m S.Pot,mV深度,mm T.A.,cm˛
1.103000 342.385783 44.343862 -0.278713 NaN 0.060977 -2.867612 5.000000
2.233000 342.357189 44.340159 -0.278713 NaN 0.069688 -5.336944 5.000000
3.356000 342.128434 44.310532 -0.202736 NaN 0.087109 -8.045245 5.000000
4.488000 341.999759 44.293867 -0.202736 NaN 0.093643 0.318624 5.000000
我想为x
数据-AreA,cm
和y
数据-PiA,mN/m
创建线性图。
很遗憾,我无法跳过第一行,因此数据无法正确加载。
我正在尝试这个:
import numpy as np
import matplotlib.pyplot as plt
with open('v10.txt') as f:
data = np.loadtxt(f, delimiter="\t", dtype='float',skiprows=0,)
x = data[:, 1]
y = data[:, 5]
fig = plt.figure()
fig.suptitle('')
plt.xlabel('')
plt.ylabel('')
plt.plot(-x, -y, c='r', label='')
leg = plt.legend()
plt.show()
任何人都知道该怎么做吗?
提前谢谢!
答案 0 :(得分:0)
以下是使用您提供的数据的解决方案。您只需要在访问文件内容时跳过文件的第一行
import numpy as np
import matplotlib.pyplot as plt
with open("file.txt") as f:
lines = f.readlines()
x = [float(line.split()[1]) for line in lines[1:]] # [1:] skips the first line
y = [float(line.split()[4]) for line in lines[1:]]
xmesh = np.linspace(min(x), max(x), 100) # Create a fine x mesh for fitting
fit = np.poly1d(np.polyfit(x,y,1)) # Making a linear fit
plt.plot(x, y, 'bo', label='Actual data') # Plotting actual data
plt.plot(xmesh, fit(xmesh), '-b', label='Linear fit') # Plotting fit
plt.xlabel('Area (cm)')
plt.ylabel('Pi A (mN/m)')
plt.legend()
输出
答案 1 :(得分:0)
使用熊猫解决方案(您可以使用$ pip install pandas
安装)
import pandas as pd
import matplotlib.pyplot as plt
filepath = 'path/to/file.txt'
df = pd.read_csv(filepath, sep=r'\s+')
area_key = 'AreaA,cm˛' # watch out for unicode '˛'
pi_key = 'PiA,mN/m'
ax = df.plot(area_key, pi_key, 'scatter', label='data') # can pass any plt kwargs here
x = df[area_key]
y = df[pi_key]
xmesh = np.linspace(min(x), max(x), 100) # Create a fine x mesh for fitting
fit = np.poly1d(np.polyfit(x,y,1)) # Making a linear fit
# cam override x/y labels titles here
ax.plot(xmesh, fit(xmesh), label='linear fit')
ax.legend()
plt.show()