解决Python音频处理库Librosa绘制频谱图报错'AxesSubplot' object has no attribute 'get_array'
使用Librosa绘制频谱图时解决'AxesSubplot' object has no attribute 'get_array'错误
在使用Python音频处理库Librosa绘制频谱图时,可能会遇到以下错误:
'AxesSubplot' object has no attribute 'get_array'
问题原因
该错误通常发生在使用fig.colorbar()函数时,这是由于Librosa库的版本问题导致的。
解决方案
要解决该问题,只需要在使用fig.colorbar()函数时添加一个参数shrink,并将其设置为小于1的值即可。
示例代码
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
matplotlib.use('Agg')
# 加载两个音频文件
y1, sr1 = librosa.load('p232_036.wav')
y2, sr2 = librosa.load('enhanced_p232_036.wav')
# 绘制波形图
plt.subplot(2, 2, 1)
librosa.display.waveplot(y1, sr=sr1)
plt.title('Audio 1')
plt.subplot(2, 2, 3)
librosa.display.waveplot(y2, sr=sr2)
plt.title('Audio 2')
# 计算并绘制频谱图
D1 = librosa.amplitude_to_db(librosa.stft(y1), ref=np.max)
D2 = librosa.amplitude_to_db(librosa.stft(y2), ref=np.max)
fig, axs = plt.subplots(2, 2)
img1 = librosa.display.specshow(D1, y_axis='linear', x_axis='time', sr=sr1, ax=axs[0, 1])
fig.colorbar(img1, ax=axs[0, 1], format='%+2.0f dB', shrink=0.7) # 添加shrink参数
axs[0, 1].set_title('Audio 1')
axs[0, 1].set_yscale('log')
img2 = librosa.display.specshow(D2, y_axis='linear', x_axis='time', sr=sr2, ax=axs[1, 1])
fig.colorbar(img2, ax=axs[1, 1], format='%+2.0f dB', shrink=0.7) # 添加shrink参数
axs[1, 1].set_title('Audio 2')
axs[1, 1].set_yscale('log')
plt.tight_layout()
plt.show()
解释
shrink参数控制颜色条的大小,将其设置为小于1的值可以缩小颜色条,从而避免错误发生。
通过以上修改,您应该能够成功绘制频谱图,而不会再遇到“'AxesSubplot' object has no attribute 'get_array'”错误。
原文地址: https://www.cveoy.top/t/topic/nqQc 著作权归作者所有。请勿转载和采集!