Search code examples
pythonmatplotlibcolorbar

Standalone colorbar


I'm rendering some graphics in python with matplotlib, and will include them into a LaTeX paper (using LaTex's nice tabular alignment instead of fiddling with matplotlib's ImageGrid, etc.). I would like to create and save a standalone colorbar with savefig, without needing to use imshow.

(the vlim, vmax parameters, as well as the cmap could be provided explicitly)

The only way I could find was quite complicated and (from what I understand) draws a hard-coded rectangle onto the canvas: http://matplotlib.org/examples/api/colorbar_only.html

Is there an elegant way to create a standalone colorbar with matplotlib?


Solution

  • You can create some dummy image and then hide it's axe. Draw your colorbar in a customize Axes.

    import pylab as pl
    import numpy as np
    
    a = np.array([[0,1]])
    pl.figure(figsize=(9, 1.5))
    img = pl.imshow(a, cmap="Blues")
    pl.gca().set_visible(False)
    cax = pl.axes([0.1, 0.2, 0.8, 0.6])
    pl.colorbar(orientation="horizontal", cax=cax)
    pl.savefig("colorbar.pdf")
    

    the result:

    enter image description here