Python折线图

2024-03-28 13:50:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,格式如下:

时间,秒A区,厘米A区,厘米B区,厘米B区,厘米PiA,毫微秒S.Pot,毫伏深度,毫米T.A.,厘米
103000 342.385783 44.343862-0.278713南0.060977-2.867612 5.000000
2233000 342.357189 44.340159-0.278713南0.069688-5.336944 5.000000
3.356000 342.128434 44.310532-0.202736南0.087109-8.045245 5.000000
4.488000 341.999759 44.293867-0.202736南0.093643 0.318624 5.000000

我想为x数据-AreA,cmy数据-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()

谁都知道怎么做?你知道吗

提前谢谢!你知道吗


Tags: 数据importdataas格式np时间fig
2条回答

使用pandas的解决方案(可以使用$ 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()

enter image description here

下面是一个使用您提供的数据的解决方案。访问文件内容时,只需跳过文件中的第一行即可

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()

输出

enter image description here

相关问题 更多 >