使用频谱图作为基础计算频谱特征时,出现了错误 'QuadMesh' object has no attribute 'plot'
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport librosa as lrfrom librosa.core import stft, amplitude_to_dbfrom librosa.display import specshowHOP_LENGTH = 2**4SIZE_WINDOW = 2**7# For the testspec = pd.read_csv('spec.csv', index_col=0)spec = np.array(np.abs(spec))time = np.array(normal.index)audio = pd.read_csv('audio.csv', index_col=0).to_numpy().squeeze()sfreq = 2205# Calculate the spectral centroid and bandwidth for the spectrogrambandwidths = lr.feature.spectral_bandwidth(S=spec)[0]centroids = lr.feature.spectral_centroid(S=spec)[0]# Convert spectrogram to decibels for visualizationspec_db = amplitude_to_db(spec)# Display these features on top of the spectrogramfig, ax = plt.subplots(figsize=(10, 5))ax = specshow(spec_db, x_axis='time', y_axis='hz', hop_length=HOP_LENGTH)ax.plot(times_spec, centroids)ax.fill_between(times_spec, centroids - bandwidths / 2, centroids + bandwidths / 2, alpha=.5)ax.set(ylim=[None, 6000])plt.show()
---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-47-896743695f65> in <module>() 15 fig, ax = plt.subplots(figsize=(10, 5)) 16 ax = specshow(spec_db, x_axis='time', y_axis='hz', hop_length=HOP_LENGTH)---> 17 ax.plot(times_spec, centroids) 18 ax.fill_between(times_spec, centroids - bandwidths / 2, centroids + bandwidths / 2, alpha=.5) 19 ax.set(ylim=[None, 6000])AttributeError: 'QuadMesh' object has no attribute 'plot'
期望的输出
回答:
你已经创建了一个子图,使用
fig, ax = plt.subplots(figsize=(10, 5))
所以不要使用
ax = specshow(spec_db, x_axis='time', y_axis='hz', hop_length=HOP_LENGTH)
你应该将子图(Axes)传递给它使用。
specshow(spec_db, ax=ax, x_axis='time', y_axis='hz', hop_length=HOP_LENGTH)