我正在尝试实现 wav 文件的瀑布图。在我的尝试中,我注意到这基本上是 3d 中的光谱图(或接近我需要的)。我正在尝试使用 numpy 和 matplotlib 在 Python 中执行此操作。
我的主要问题是我不知道如何将光谱图从 matplotlib 更改为 3d 绘图。
我的“代码”示例:
sample ,data = wavfile.read('file.wav')
F = Figure()
a = F.add_subplot(111,projection='3d')
Spec, t, freq, im = a.specgram(data,Fs=2)
我已经走了这么远,不知道下一步要做什么。我想将现有的情节更改为 3d。由于缺乏知识,我没有将其更改为 3d 的代码。
是否可以将 2d 绘图转换为 3d ?如果是这样怎么办?我最好用光谱图的数据构建一个新图吗?
期望的结果类似于以下内容:
感谢您的任何答复。
最佳答案
以下是来自 scipy 的示例信号的 3D 和 2D 频谱图。您可以在本文末尾找到 page .
from matplotlib import mlab
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(666)
title = ('2 Vrms sine wave with modulated frequency around 3kHz, '
'corrupted by white noise of exponentially decreasing '
'magnitude sampled at 10 kHz.')
fs = 10e3
N = 1e5
amp = 2 * np.sqrt(2)
noise_power = 0.01 * fs / 2
t = np.arange(N) / float(fs)
mod = 500*np.cos(2*np.pi*0.25*t)
carrier = amp * np.sin(2*np.pi*3e3*t + mod)
noise = np.random.normal(scale=np.sqrt(noise_power), size=t.shape)
noise *= np.exp(-t/5)
y = carrier + noise
def specgram3d(y, srate=44100, ax=None, title=None):
if not ax:
ax = plt.axes(projection='3d')
ax.set_title(title, loc='center', wrap=True)
spec, freqs, t = mlab.specgram(y, Fs=srate)
X, Y, Z = t[None, :], freqs[:, None], 20.0 * np.log10(spec)
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_xlabel('time (s)')
ax.set_ylabel('frequencies (Hz)')
ax.set_zlabel('amplitude (dB)')
ax.set_zlim(-140, 0)
return X, Y, Z
def specgram2d(y, srate=44100, ax=None, title=None):
if not ax:
ax = plt.axes()
ax.set_title(title, loc='center', wrap=True)
spec, freqs, t, im = ax.specgram(y, Fs=fs, scale='dB', vmax=0)
ax.set_xlabel('time (s)')
ax.set_ylabel('frequencies (Hz)')
cbar = plt.colorbar(im, ax=ax)
cbar.set_label('Amplitude (dB)')
cbar.minorticks_on()
return spec, freqs, t, im
fig1, ax1 = plt.subplots()
specgram2d(y, srate=fs, title=title, ax=ax1)
fig2, ax2 = plt.subplots(subplot_kw={'projection': '3d'})
specgram3d(y, srate=fs, title=title, ax=ax2)
plt.show()
奖金:您可以通过使用 scipy 创建 wav 文件来收听信号:
from scipy.io import wavfile
wavfile.write('sig.wav', int(fs), y)
关于python - 如何将频谱图转换为 3d 图。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598829/