서브 플롯이있는 matplotlib에서 고정 된 x 축으로 2 개의 애니메이션 그래픽을 그리는 방법은 무엇입니까?

가브리엘 바스 토스

프로그램의 목적 : 상단에는 신호 그래픽을, 하단에는이 신호의 스펙트럼 그래픽을 플로팅해야합니다. 두 경우 모두 y 데이터 만 다릅니다.

입력에 무작위 노이즈가있는 사인파를 생성하고 상단에 플로팅합니다. 완벽하게 작동합니다.

문제는 스펙트럼 그래프를 그리려고 할 때입니다. 어떤 이유로 업데이트되지 않고 matplotlib.animation.FuncAnimation의 기능을 잘 이해하지 못했습니다.

코드:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

dt = 0.01
Fs = 44000.0              # sample rate
timestep = 1.0/Fs         # sample spacing (1/sample rate)
t = np.arange(0, 10, dt)  # t range
n = 256                   # size of the array data
w = 10000                 # frequency of the input

data = np.sin(2*np.pi*w*t)



def update(data):
    # update the curves with the incoming data
    line.set_ydata(data)
    #line2.set_ydata(magnitude)

    return line,

def generateData():
    # simulate new data coming in
    while True:
        nse = np.random.randn(len(t))
        r = np.exp(-t/0.05)
        cnse = np.convolve(nse, r)*dt
        cnse = cnse[:len(t)]
        data =  np.sin(2*np.pi*w*(t)) + cnse
        magnitude = np.fft.fft(data)/n
        magnitude = np.abs(magnitude[range(n//2)])
        yield data

fig = plt.figure()

# plot time graph axis
timeGraph = plt.subplot(2, 1, 1)
timeGraph.set_ylim(-0.2, 0.2)
timeGraph.set_xlabel('Time')
timeGraph.set_ylabel('Amplitude')

# plot frequency graph axis
freqGraph = plt.subplot(2, 1, 2)
freqGraph.set_xlabel('Freq (Hz)')
freqGraph.set_ylabel('|Y(freq)|')

# get frequency range
n = len(data) # length of the signal
print(len(data))
k = np.arange(n)
T = n/Fs
freq = k/T # two sides frequency range
freq = freq[range(n//2)] # one side frequency range

# fft computing and normalization
magnitude = np.fft.fft(data)/n
magnitude = np.abs(magnitude[range(n//2)])


line, = timeGraph.plot(np.linspace(0, 1, len(t)), 'b')
line2, = freqGraph.plot(freq, magnitude, 'g')


# animate the curves
ani = animation.FuncAnimation(fig, update, generateData,
                              interval=10, blit=True)

plt.show() # open window

보너스 : 데이터와 크기를 올바르게 초기화하려면 어떻게해야합니까?

중요성의 중요성

시간 및 빈도 그래프를 모두 업데이트하려면 두 데이터를 update함수 의 각 플롯으로 설정해야 합니다. 물론 생성 함수에서도이 데이터를 제공해야합니다. 따라서 생성 함수 yield (data, magnitude)와 업데이트 함수는이 튜플을 입력으로 받아 들여야합니다.

빈도 그래프에 대해 일부 제한을 설정하여 freqGraph.set_ylim([0, 0.006])비어 있지 않도록 하는 것도 좋은 생각 입니다.

데이터와 크기를 올바르게 초기화하는 방법이 무엇을 의미하는지 모르겠습니다 . . 첫 번째 프레임을 포함하여 모든 프레임에 대해 계산된다는 점에서 올바르게 초기화되었다고 생각합니다.

다음은 작동 코드입니다.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

dt = 0.01
Fs = 44000.0              # sample rate
timestep = 1.0/Fs         # sample spacing (1/sample rate)
t = np.arange(0, 10, dt)  # t range
n = 256                   # size of the array data
w = 10000                 # frequency of the input

data = np.sin(2*np.pi*w*t)



def update(data):
    # update the curves with the incoming data
    line.set_ydata(data[0])
    line2.set_ydata(data[1])
    return line, line2,

def generateData():
    # simulate new data coming in
    while True:
        nse = np.random.randn(len(t))
        r = np.exp(-t/0.05)
        cnse = np.convolve(nse, r)*dt
        cnse = cnse[:len(t)]
        data =  np.sin(2*np.pi*w*(t)) + cnse
        magnitude = np.fft.fft(data)/n
        magnitude = np.abs(magnitude[range(n//2)])
        yield (data, magnitude)

fig = plt.figure()

# plot time graph axis
timeGraph = plt.subplot(2, 1, 1)
timeGraph.set_ylim(-0.2, 0.2)
timeGraph.set_xlabel('Time')
timeGraph.set_ylabel('Amplitude')

# plot frequency graph axis
freqGraph = plt.subplot(2, 1, 2)
freqGraph.set_ylim([0, 0.006])
freqGraph.set_xlabel('Freq (Hz)')
freqGraph.set_ylabel('|Y(freq)|')

# get frequency range
n = len(data) # length of the signal
print(len(data))
k = np.arange(n)
T = n/Fs
freq = k/T # two sides frequency range
freq = freq[range(n//2)] # one side frequency range

# fft computing and normalization
magnitude = np.fft.fft(data)/n
magnitude = np.abs(magnitude[range(n//2)])


line, = timeGraph.plot(np.linspace(0, 1, len(t)),'b')
line2, = freqGraph.plot(freq, magnitude,'g')


# animate the curves
ani = animation.FuncAnimation(fig, update, generateData,
                              interval = 10, blit=True)

plt.show() # open window

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사