remove colorbar from figure in matplotlib

后端 未结 9 510
终归单人心
终归单人心 2020-12-08 14:14

This should be easy but I\'m having a hard time with it. Basically, I have a subplot in matplotlib that I\'m drawing a hexbin plot in every time a function is called, but ev

9条回答
  •  醉梦人生
    2020-12-08 15:08

    Don't want to take anything away from the author of this blog post (Joseph Long) but this is clearly the best solution I've found so far. It includes pieces of code, great explanations and many examples.

    To summarize, from any output of an axis ax of the command: plot, image, scatter, collection, etc. such as:

    import matplotlib.pyplot as plt
    fig = plt.figure(figsize=(5,5), dpi=300)
    ax = fig.add_subplot(1, 1, 1)
    
    data = ax.plot(x,y)
    # or
    data = ax.scatter(x, y, z)
    # or
    data = ax.imshow(z)
    # or 
    data = matplotlib.collection(patches)
    ax.add_collection(data)
    

    You create a color bar axis using the make_axes_locatable and the original axis of the plot.

    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    # the magical part
    divider = make_axes_locatable(ax)
    caxis = divider.append_axes("right", size="5%", pad=0.05)
    fig.colorbar(data, cax=caxis)
    
    plt.show()
    

    The created colorbar will have the same size as the figure or subplot and you can modify it's width, location, padding when using the divider.append_axes command.

提交回复
热议问题