Search code examples
pythonmatplotlibcolorbarobspy

Problem plotting spectrogram colorbar in matplotlib


I want to make a subplot using the input data


Solution

  • I think this is just a question of passing the spectrogram's "mappable" to plt.colorbar() so that it knows what to make a colourbar for. The tricky thing is that it's a bit buried in an attribute of the spectrogram Axes:

    fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)
    ax1.plot(time, data1[0].data)
    ax2.plot(time, data2.data)
    spec = data2.spectrogram(axes=ax3,  # <-- Assign a name.
                             show=True,
                             samp_rate=20,
                             per_lap=0.5,
                             wlen=30,
                             log=True,
                             cmap='plasma',  # <-- Don't use jet :)
                             clip=(0.05, 0.2),
                            )
    plt.xlabel('Time')
    plt.ylabel('Frequency')
    
    # More flexibility with the positioning:
    cbar_ax = fig.add_axes([0.2, 0.0, 0.6, 0.05])  # Left, bottom, width, height.
    cbar = fig.colorbar(spec.collections[0],  # <-- Get the mappable.
                        cax=cbar_ax,
                        orientation='horizontal')
    cbar.set_label('Colorbar label')
    
    plt.show()
    

    This also shows how to position the colorbar where you want. And I changed your colourmap to plasma because you shouldn't use jet.