【发布时间】:2018-06-26 07:55:32
【问题描述】:
我正在尝试使用“matplotlib.pyplot.stem”函数生成一个 Stem 图。该代码有效,但处理时间超过 5 分钟。
我在 Matlab 中有一个类似的代码,几乎可以立即用相同的输入数据生成相同的绘图。
有没有办法优化此代码以提高速度或我可以使用的更好的功能?
茎图“H”和“plotdata”的参数是 16384 x 1 数组。
def stemplot():
import numpy as np
from scipy.fftpack import fft
import matplotlib.pyplot as plt
################################################
# Code to set up the plot data
N=2048
dr = 100
k = np.arange(0,N)
cos = np.cos
pi = np.pi
w = 1-1.932617*cos(2*pi*k/(N-1))+1.286133*cos(4*pi*k/(N-1))-0.387695*cos(6*pi*k/(N-1))+0.0322227*cos(8*pi*k/(N-1))
y = np.concatenate([w, np.zeros((7*N))])
H = abs(fft(y, axis = 0))
H = np.fft.fftshift(H)
H = H/max(H)
H = 20*np.log10(H)
H = dr+H
H[H < 0] = 0 # Set all negative values in dr+H to 0
plotdata = ((np.arange(1,(8*N)+1,1))-1-4*N)/8
#################################################
# Plotting Code
plt.figure
plt.stem(plotdata,H,markerfmt = " ")
plt.axis([(-4*N)/8, (4*N)/8, 0, dr])
plt.grid()
plt.ylabel('decibels')
plt.xlabel('DFT bins')
plt.title('Frequency response (Flat top)')
plt.show()
return
这里也是matlab代码供参考:
N=2048;
dr = 100;
k=0:N-1
w = 1 - 1.932617*cos(2*pi*k/(N-1)) + 1.286133*cos(4*pi*k/(N-1)) -0.387695*cos(6*pi*k/(N-1)) +0.0322227*cos(8*pi*k/(N-1));
H = abs(fft([w zeros(1,7*N)]));
H = fftshift(H);
H = H/max(H);
H = 20*log10(H);
H = max(0,dr+H); % Sets negative numbers in dr+H to 0
figure
stem(([1:(8*N)]-1-4*N)/8,H,'-');
set(findobj('Type','line'),'Marker','none','Color',[.871 .49 0])
xlim([-4*N 4*N]/8)
ylim([0 dr])
set(gca,'YTickLabel','-100|-90|-80|-70|-60|-50|-40|-30|-20|-10|0')
grid on
ylabel('decibels')
xlabel('DFT bins')
title('Frequency response (Flat top)')
【问题讨论】:
-
你能把它设为minimal reproducible example 吗?在不知道您的
w是什么的情况下,无法运行此代码。 -
另外,
return是一个语句,而不是一个函数。后面不需要()。 -
在这种特殊情况下根本不需要它;-)
-
我可以重复第二期中的一个cmets:16384分,你确定你想要一个茎图吗?
标签: python matlab matplotlib optimization plot