调用matplotlib.mlab.psd函数时遇TypeError:意外关键字参数'Fc'
问题描述
使用matplotlib.mlab.psd函数时触发错误,代码如下:
from matplotlib.mlab import psd from rtlsdr import * import matplotlib.pyplot as plt sdr = RtlSdr() # configure device sdr.sample_rate = 2.4e6 p = sdr.center_freq = 95e6 sdr.gain = 'auto' arr_db = [] arr_fq = [] def plot_graph(): print(len(arr_db)) print(len(arr_fq)) xlabel('Frequency (MHz)') ylabel('Relative power (dB)') #plt.plot(arr_db, arr_fq, color='blue') plt.draw() plt.pause(0.5) plt.clf() while True: # use matplotlib to estimate and plot the PSD samples = sdr.read_samples(256*1024) a = psd(samples.real, NFFT=1024, Fs=sdr.sample_rate/1e6, Fc=p/1e6) p+= 1000000 for i in range(513): b = a[0][i] c = a[1][i] arr_db.append(b) arr_fq.append(c) plot_graph() sdr.close()
报错信息:
Traceback (most recent call last): File "c:\Users\DELL\Desktop\Ismail\rtl_sdr\sample.py", line 27, in <module> a = psd(samples.real, NFFT=1024, Fs=sdr.sample_rate/1e6, Fc=p/1e6) TypeError: psd() got an unexpected keyword argument 'Fc' Found Rafael Micro R820T/2 tuner
解决办法
- 移除无效参数
Fc:matplotlib.mlab.psd函数不支持Fc参数,这是报错的直接原因。该函数返回的频率轴是相对于采样率中心的偏移值,需手动加上实际中心频率得到真实频率。 - 修正绘图API调用:
xlabel和ylabel需要添加plt.前缀,否则会触发NameError。 - 优化数据处理逻辑:原代码持续累积所有PSD数据会导致数组无限增大,绘图效率下降且显示混乱,建议每次仅使用当前采样的PSD结果绘图。
修改后的代码:
from matplotlib.mlab import psd from rtlsdr import * import matplotlib.pyplot as plt sdr = RtlSdr() # configure device sdr.sample_rate = 2.4e6 p = sdr.center_freq = 95e6 sdr.gain = 'auto' def plot_graph(power, freq): plt.xlabel('Frequency (MHz)') plt.ylabel('Relative power (dB)') plt.plot(freq, power, color='blue') plt.draw() plt.pause(0.5) plt.clf() while True: # use matplotlib to estimate and plot the PSD samples = sdr.read_samples(256*1024) # 移除Fc参数,手动计算真实频率 power, freq = psd(samples.real, NFFT=1024, Fs=sdr.sample_rate/1e6) # 将相对频率加上中心频率,得到真实频率 actual_freq = freq + p/1e6 p += 1000000 plot_graph(power, actual_freq) sdr.close()
内容的提问来源于stack exchange,提问作者ismail
相关产品推荐
相关产品推荐

