Add colorbar to existing axis

前端 未结 3 541
[愿得一人]
[愿得一人] 2020-12-04 10:55

I\'m making some interactive plots and I would like to add a colorbar legend. I don\'t want the colorbar to be in its own axes, so I want to add it to the existing axes. I\'

3条回答
  •  余生分开走
    2020-12-04 11:41

    This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:

    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    data = np.arange(100, 0, -1).reshape(10, 10)
    
    fig, ax = plt.subplots()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='5%', pad=0.05)
    
    im = ax.imshow(data, cmap='bone')
    
    fig.colorbar(im, cax=cax, orientation='vertical')
    plt.show()
    

提交回复
热议问题