python - matplotlib 茎图的优化

标签 python matlab matplotlib optimization plot

我正在尝试使用“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)')

最佳答案

您可以使用 ax.vlines 以您想要的格式模拟一个针状图。编写一个小函数,

def make_stem(ax, x, y, **kwargs):
    ax.axhline(x[0],x[-1],0, color='r')

    ax.vlines(x, 0, y, color='b')

    ax.set_ylim([1.05*y.min(), 1.05*y.max()])

然后如下更改示例中的相关行:

    # Plotting Code

##    plt.figure
##    plt.stem(plotdata,H,markerfmt = " ")

##    plt.axis([(-4*N)/8, (4*N)/8, 0, dr])

    fig, ax = plt.subplots()
    make_stem(ax, plotdata, H)

或多或少立即产生情节。但是,我不知道这比@ImportanceOfBeingErnest 的回答更快还是更慢。

关于python - matplotlib 茎图的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48301044/

相关文章:

python - 使用 pandas groupby 创建 df 的子集并根据函数获取值

matlab - Matlab可以识别数据类型吗?

matlab - 按某些颜色的像素对 jet 颜色图进行分类

python - 如何使饼图标签与数据框中的正确值保持一致?

python - Django休息框架: Find URL for hyperlinked model

python - 使用numpy的调色板方法

matlab - Parfor切片变量导致Matlab崩溃

python - matplotlib 中的刻度线

python - pandas 星期几轴标签

python - 使用 biopython 从外部 pubmed ID 列表中提取多个摘要