Python 向光谱图添加颜色条

Python 向光谱图添加颜色条,python,python-2.7,spectrogram,Python,Python 2.7,Spectrogram,我想在光谱图上加一个色条。我已经尝试了我在网上找到的每一个例子和问题线索,没有一个解决了这个问题 请注意,“spl1”(数据拼接1)是来自ObsPy的跟踪 我的代码是: fig = plt.figure() ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height] ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1) ax3 = fig.add_axes([0.

我想在光谱图上加一个色条。我已经尝试了我在网上找到的每一个例子和问题线索,没有一个解决了这个问题

请注意,“spl1”(数据拼接1)是来自ObsPy的跟踪

我的代码是:

fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]
ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)
ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])

t = np.arange(spl1[0].stats.npts) / spl1[0].stats.sampling_rate
ax1.plot(t, spl1[0].data, 'k')

ax,spec = spectrogram(spl1[0].data,spl1[0].stats.sampling_rate, show=False, axes=ax2)
ax2.set_ylim(0.1, 15)
fig.colorbar(spec, cax=ax3)
结果出现了一个错误:

Traceback (most recent call last):

  File "<ipython-input-18-61226ccd2d85>", line 14, in <module>
    ax,spec = spectrogram(spl1[0].data,spl1[0].stats.sampling_rate, show=False, axes=ax2)

TypeError: 'Axes' object is not iterable
产生以下结果:

颜色栏的此错误:

axes object has no attribute 'autoscale_None'
from obspy.imaging.spectrogram import spectrogram
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]
ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)
ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])

#make time vector
t = np.arange(spl1[0].stats.npts) / spl1[0].stats.sampling_rate

#plot waveform (top subfigure)    
ax1.plot(t, spl1[0].data, 'k')

#plot spectrogram (bottom subfigure)
spl2 = spl1[0]
fig = spl2.spectrogram(show=False, axes=ax2)
mappable = ax2.images[0]
plt.colorbar(mappable=mappable, cax=ax3)
我似乎找不到一种方法让彩色条在右边工作

解决方案?

我看到的一个解决方案是,您需要使用imshow()创建数据的“图像”,但是我没有从Spectrogram()中获得输出,只有“ax”。我见过一些地方尝试使用spectrogram()的“ax,spec”输出,但这导致了类型错误

  • 我发现的代码非常相似,但不起作用(ctrl+f‘colorbar’)
  • 查看代码示例
  • imshow()和-无法从光谱图获得输出以转换为图像。第二个链接,我也不能让mlpy模块工作(它认为没有mlpy.wavelet函数)
  • 这个问题在中得到了解决,但他说他找到的解决方案没有给出

我希望有人能帮上忙——我已经为此工作了一整天了

我假设您正在使用。它以颜色的形式大张旗鼓地呼吁颜色
matplotlib.pyplot.plot(x坐标、y坐标、颜色)

下面是一个示例实现

"""Plots
Time in MS Vs Amplitude in DB of a input wav signal
"""

import numpy
import matplotlib.pyplot as plt
import pylab
from scipy.io import wavfile
from scipy.fftpack import fft


myAudio = "audio.wav"

#Read file and get sampling freq [ usually 44100 Hz ]  and sound object
samplingFreq, mySound = wavfile.read(myAudio)

#Check if wave file is 16bit or 32 bit. 24bit is not supported
mySoundDataType = mySound.dtype

#We can convert our sound array to floating point values ranging from -1 to 1 as follows

mySound = mySound / (2.**15)

#Check sample points and sound channel for duel channel(5060, 2) or  (5060, ) for mono channel

mySoundShape = mySound.shape
samplePoints = float(mySound.shape[0])

#Get duration of sound file
signalDuration =  mySound.shape[0] / samplingFreq

#If two channels, then select only one channel
mySoundOneChannel = mySound[:,0]

#Plotting the tone

# We can represent sound by plotting the pressure values against time axis.
#Create an array of sample point in one dimension
timeArray = numpy.arange(0, samplePoints, 1)

#
timeArray = timeArray / samplingFreq

#Scale to milliSeconds
timeArray = timeArray * 1000

#Plot the tone
plt.plot(timeArray, mySoundOneChannel, color='G')
plt.xlabel('Time (ms)')
plt.ylabel('Amplitude')
plt.show()


#Plot frequency content
#We can get frquency from amplitude and time using FFT , Fast Fourier Transform algorithm

#Get length of mySound object array
mySoundLength = len(mySound)

#Take the Fourier transformation on given sample point 
#fftArray = fft(mySound)
fftArray = fft(mySoundOneChannel)

numUniquePoints = numpy.ceil((mySoundLength + 1) / 2.0)
fftArray = fftArray[0:numUniquePoints]

#FFT contains both magnitude and phase and given in complex numbers in real + imaginary parts (a + ib) format.
#By taking absolute value , we get only real part

fftArray = abs(fftArray)

#Scale the fft array by length of sample points so that magnitude does not depend on
#the length of the signal or on its sampling frequency

fftArray = fftArray / float(mySoundLength)

#FFT has both positive and negative information. Square to get positive only
fftArray = fftArray **2

#Multiply by two (research why?)
#Odd NFFT excludes Nyquist point
if mySoundLength % 2 > 0: #we've got odd number of points in fft
    fftArray[1:len(fftArray)] = fftArray[1:len(fftArray)] * 2

else: #We've got even number of points in fft
    fftArray[1:len(fftArray) -1] = fftArray[1:len(fftArray) -1] * 2  

freqArray = numpy.arange(0, numUniquePoints, 1.0) * (samplingFreq / mySoundLength);

#Plot the frequency
plt.plot(freqArray/1000, 10 * numpy.log10 (fftArray), color='B')
plt.xlabel('Frequency (Khz)')
plt.ylabel('Power (dB)')
plt.show()

#Get List of element in frequency array
#print freqArray.dtype.type
freqArrayLength = len(freqArray)
print "freqArrayLength =", freqArrayLength
numpy.savetxt("freqData.txt", freqArray, fmt='%6.2f')

#Print FFtarray information
print "fftArray length =", len(fftArray)
numpy.savetxt("fftData.txt", fftArray)
在来自的帮助下解决了这个问题。它还没有显示分贝,但主要问题是颜色条:

axes object has no attribute 'autoscale_None'
from obspy.imaging.spectrogram import spectrogram
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]
ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)
ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])

#make time vector
t = np.arange(spl1[0].stats.npts) / spl1[0].stats.sampling_rate

#plot waveform (top subfigure)    
ax1.plot(t, spl1[0].data, 'k')

#plot spectrogram (bottom subfigure)
spl2 = spl1[0]
fig = spl2.spectrogram(show=False, axes=ax2)
mappable = ax2.images[0]
plt.colorbar(mappable=mappable, cax=ax3)

您是否成功绘制了没有色条的光谱图?您正在使用的
光谱图
函数(来自哪个库)是什么?@gsmafra我已经用更多信息更新了上面的帖子-我可以让光谱图正常绘图是的。spectrogram函数来自:obspy.imaging.spectrogram.spectrogram(因为它具有更简单的内置功能)-尽管在下面它使用specgram正在进行中的讨论,其中有一个成功的色条图。不适合我的情况,但是如果在那里找到了解决方案,那么我也会在这里添加解决方案。嘿,对不起,我认为你不理解这个问题。我可以更改线条图等的颜色,但我想在光谱图中添加一个色条(如z轴色条,指示与颜色相关的值范围)