【问题标题】:Remove the microseconds from matplotlib spectrogram从 matplotlib 频谱图中删除微秒
【发布时间】:2018-11-23 08:06:38
【问题描述】:

我一直在尝试根据 15 分钟长的 wav 文件绘制频谱图。我想我设法做到了,但我无法从我的 x 轴(时间轴)中删除微秒。请问有这方面的帮助吗?

这是获得的频谱图:

这是我的代码:

import matplotlib.pyplot as plt
import scipy.io.wavfile as wavfile
import matplotlib.ticker as ticker
from matplotlib.dates import DateFormatter, MinuteLocator
import time 
# Prettify
import matplotlib
import datetime
matplotlib.rc('figure', figsize=(17, 5))

cmap = plt.get_cmap('plasma') # this may fail on older versions of matplotlib
vmin = -40  # hide anything below -40 dB
cmap.set_under(color='k', alpha=None)

rate, frames = wavfile.read("audio_test.wav")
fig, ax = plt.subplots()
pxx, freq, t, cax = ax.specgram(frames[:, 0], # first channel
                                Fs=rate,      # to get frequency axis in Hz
                                cmap=cmap, vmin=vmin)
cbar = fig.colorbar(cax)
cbar.set_label('Intensity dB')
ax.axis("tight")



ax.set_xlabel('time h:mm:ss')
ax.set_ylabel('frequency kHz')

scale = 1e3                     # KHz
ticks = matplotlib.ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale))
ax.yaxis.set_major_formatter(ticks)

def timeTicks(x, pos):
    d = datetime.timedelta(seconds=x)
    return str(d)
#formatter = matplotlib.ticker.FuncFormatter(timeTicks)
#ax.xaxis.set_major_formatter(formatter)

majorFormatter = matplotlib.dates.DateFormatter('%H:%M:%S') 
ax.xaxis.set_major_formatter(majorFormatter)
ax.xaxis.set_major_locator(ticker.IndexLocator(base=120, offset=60))
#ax.text(0.0, 0.1, "IndexLocator(base=0.5, offset=0.25)",
#        fontsize=14, transform=ax.transAxes)
plt.show()

【问题讨论】:

  • 你能发布一个数据样本吗?
  • 你好@乔!不完全的。这是一个具有不同音频声音的“.wav”文件。但我不允许分享它:(
  • 你可以试试这样的:majorFormatter = matplotlib.dates.DateFormatter('%H:%M:%S')ax.xaxis.set_major_formatter(majorFormatter)
  • 谢谢@Joe!它有点工作。但它在时间轴上只显示“00:02:05”。我将更新频谱图和代码的照片。不知道为什么会这样...
  • @Joe 它返回一个错误:TypeError: 'datetime.timedelta' object is not subscriptable

标签: python matplotlib spectrogram


【解决方案1】:

使用代码编辑前,您可以更改def timeTicks(x, pos) 中的return

return str(d)[:7]

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    相关资源
    最近更新 更多