I'm trying to produce a Stem plot using the 'matplotlib.pyplot.stem' function. The code works but it is taking over 5 minutes to process.
I have a similar code within Matlab that produces the same plot with the same input data almost instantly.
Is there a way to optimize this code for speed or a better function I could be using?
The arguments for the stem plot 'H' and 'plotdata' are 16384 x 1 arrays.
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
Here is also the Matlab code for reference:
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)')
wis, this code cannot be run.returnis a statement, not a function. No need for the()after it.