Pyplot绘制索引而不是datafram的值

2024-10-01 11:37:50 发布

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

我正在尝试做一个程序,能够转换一个不同长度的csv到一个数据帧。然后,我试图绘制数据帧的特定列,x值是索引除以1000(采样率是1000Hz)。在

但是,我有一个奇怪的交互,它以线性的方式绘制列的值,并将该点标记为一个值。它可能会绘制索引值,但我不确定,因为输出是一条曲线。 我使用的当前数据集是大约12台设备的5000多个数据点(所有这些都是同时采样的)。我将展示下面的数据片段。在

输出如下: enter image description here 右图是左图值的fft。在

输出应该是这样的: enter image description here 右边的图形对两者都是相同的,这是正确的输出。这告诉我,左图的图有点奇怪,但是整个代码没有错。在

这是我的代码:

from scipy import fftpack
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import csv
temp = []
samplerate = 1000

with open('C:/Users/sword/Anaconda3/envs/exceltest/RF_SubjP02_Free_STATIC_TR02.csv', 'r') as csvfile:
  csvreader = csv.reader(csvfile, delimiter=',')
  for row in csvreader:
     if csvreader.line_num == 3:
         temp.append(row)
     if csvreader.line_num >= 6:
        if row:
            temp.append(row)
        else:
            break
df = pd.DataFrame(temp) #turns the array into a dataframe
df.columns = df.iloc[0] #sets the column names as the first row
df = df.drop(0) #drops the first row since it is now a duplicate of the column names 
emg1 = df['Noraxon Desk Receiver - EMG1']
horiz = np.arange(0,len(emg1)/samplerate,1/samplerate) #getting the time domain in seconds

emgfft = fftpack.fft(emg1, horiz.size)  #fft of the emg
emgfftabs = np.abs(emgfft) #absolute value of the fft values
xf = fftpack.fftfreq(horiz.size, (len(emg1) / samplerate) / samplerate) #frequency range

plt.figure()
plt.subplot(1,2,1)
plt.plot(horiz, emg1) #tried this one and the one below with the same result, both gave the wrong curved graph from the first picture
plt.plot(df['Noraxon Desk Receiver - EMG1']) #I didn't use both at the same time
ticks = plt.yticks(df['Noraxon Desk Receiver - EMG1'].values[::100]) #this is just here to make it readable, otherwise the y labels are a solid black bar

plt.subplot(1,2,2)
plt.plot(xf[0:len(xf)//2],2*emgfftabs[0:len(emgfftabs)//2])
plt.show()

注意'Noraxon Desk Receiver-EMG1'是我在csv文件中将其重命名为'EMG1'之前的原始列名。在

下面是一个数据集示例

enter image description here

emg1的值可能有助于了解

enter image description here

这个指数似乎与我所能判断的数值不可分离。emg1的数据类型最终是“object”。我尝试过使用“.tolist()”,但也没用。在

任何帮助解决这个问题将不胜感激!在


Tags: csvthe数据importfftdfasplt
2条回答

使用df = pd.read_csv('your/csv/location.csv', index_col='your_index')可以简化事情。在

所以如果你想对你的csv中的“索引”执行这个操作:

df['index'] = df['index'] / 1000

然后:

^{pr2}$

应同时绘制emg1和emg2、em3等。如果只想绘制emg1和emg2,则必须指定它。在

在我看来,你只是在绘制emg1(正)值,所以matplotlib没有给出反射声波的形状。在

我找到了答案。显然,csvreader实际上是把科学符号当作字符串来读的。我刚加了句台词

emg1 = emg1.astype(np.float)

而且效果很好。在

相关问题 更多 >