Add colorbar to existing axis

前端 未结 3 540
[愿得一人]
[愿得一人] 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:33

    The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

    For example:

    import numpy as np
    import matplotlib.pyplot as plt
    
    data = np.arange(100, 0, -1).reshape(10, 10)
    
    fig, ax = plt.subplots()
    cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
    
    im = ax.imshow(data, cmap='gist_earth')
    fig.colorbar(im, cax=cax, orientation='horizontal')
    plt.show()
    

提交回复
热议问题