简体   繁体   English

一张图中的多个图 matplotlib python signal.welch

[英]multiple plots in one figure matplotlib python signal.welch

I try to plot 3 plots for each columns ('AFp1','AFp2','F9') in one figure with 'freqs' on the x axis and 'psd' on the y axis.我尝试在一个图中为每列('AFp1'、'AFp2'、'F9')绘制 plot 3 个图,其中 x 轴为“freqs”,y 轴为“psd”。 I'm looking for a kind of loop through the variables because at the end I want to plot >50 plots in one figure.我正在寻找一种通过变量的循环,因为最后我想在一个图中 plot >50 个图。

Here I found a code that seems to do what I want but I don't get it to work: 在这里,我找到了一个似乎可以做我想做的事情但我没有让它工作的代码:

num_plots = 20

colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))

x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
    plt.plot(x, i * x + 5 * i)
    labels.append(r'$y = %ix + %i$' % (i, 5*i))

plt.legend(labels, ncol=4, loc='upper center', 
           bbox_to_anchor=[0.5, 1.1], 
           columnspacing=1.0, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)

plt.show()

Here is how I tried to include this code in my for loop:以下是我尝试将此代码包含在我的 for 循环中的方法:

path = r'C:/M'
for fil in os.listdir(path):
    #extract SUBJECT name
    r = (fil.split(" ")[0])
    #load file in pandas dataframe
    data = pd.read_csv(path+f'{r} task.txt',sep=",",usecols= 'AFp1','AFp2','F9'])
    data.columns = ['AFp1','AFp2','F9']
    
   num_plots = 3
    for columns in data(1, num_plots + 1):
        freqs, psd = signal.welch(data[columns], fs=500,
                                  window='hanning',nperseg=1000, noverlap=500, scaling='density', average='mean')
        
        colormap = plt.cm.gist_ncar
        plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))
        
        plt.plot(freqs, psd)
        plt.legend(columns, ncol=4, loc='upper center', 
                   bbox_to_anchor=[0.5, 1.1], 
                   columnspacing=1.0, labelspacing=0.0,
                   handletextpad=0.0, handlelength=1.5,
                   fancybox=True, shadow=True)
        plt.title(f'PSD for {r}')#, nperseg=1000, noverlap=500
        plt.xlabel('Frequency [Hz]')
        plt.ylabel('Power [V**2/Hz]')
        plt.axis([0,50, -1, 5])
               
        plt.show()

I get the following error:我收到以下错误:

   for columns in data(1, num_plots + 1):

TypeError: 'DataFrame' object is not callable 

If anyone could tell me how I can make it work, it would be great:D如果有人能告诉我如何使它工作,那就太好了:D

Thank you very much, Angelika非常感谢,安吉丽卡

Shoaib's answer finally worked. Shoaib 的回答终于奏效了。 Thank you very much: "you should only use plt.show() once, so put it outside of for loop. your error is because data is an array but you used it as a function like data(something) . you should see what is dimensions of data and then try to select columns or values using data[ something ] not data( something ). check dimensions of data using codes like print(data) or print(data[0]) or print(len(data)) or print(len(data[0])) etc. it will help you in debugging your code "非常感谢:“你应该只使用plt.show()一次,所以把它放在 for 循环之外。你的错误是因为 data 是一个数组,但你把它用作 function 之类的data(something) 。你应该看看什么是数据的维度,然后尝试 select 列或值使用data[ something ]而不是data( something ). 使用print(data)print(data[0])print(len(data))等代码检查数据的维度或print(len(data[0]))等,它将帮助您调试代码“

here is how you plot three functions in a figure这里是你如何 plot 三个函数在一个图中

import matplotlib.pyplot as plt
from math import *

x_lim = 6
n = 1000
X = []
Y1 = []
Y2 = []
Y3 = []
for i in range(n):
    x = x_lim * (i/n-1)
    y1 = sin(x)
    y2 = cos(x)
    y3 = x**2
    X.append( x )
    Y1.append( y1 )
    Y2.append( y2 )
    Y3.append( y3 )
    
plt.plot(X,Y1)
plt.plot(X,Y2)
plt.plot(X,Y3)
plt.title("title")
plt.xlabel("x")
plt.ylabel("y")
plt.show()

your question was not reproducible, because the file you are getting your data from is not entailed.您的问题不可重现,因为您从中获取数据的文件不是必需的。 so we can not reproduce your error with copy paste your code.因此我们无法通过复制粘贴您的代码来重现您的错误。 but if you have an array namely data with for example 4 columns then you can separate each columns then plot them但是如果你有一个数组,即data ,例如 4 列,那么你可以将每一列分开,然后 plot 它们

for row in data:
    x.append( row[0] )
    Y1.append( row[1] )
    Y2.append( row[2] )
    Y3.append( row[3] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM