Python colorbar from scratch#

Software requirements:

  • Python 3

  • matplotlib

Example script#

colorbar_from_scratch.py

#!/usr/bin/env python
# coding: utf-8
'''
DKRZ example

Create colorbar from scratch (stand alone)

Content

- create a colorbar from RGB-values
- create a colorbar without the need of a mappable object using
      matplotlib.colorbar.Colorbar()
- write custom labels below each color box
- write a colorbar title string
- save colorbar figure to PNG file

See https://matplotlib.org/stable/api/colorbar_api.html#matplotlib.colorbar.Colorbar

-------------------------------------------------------------------------------
2022 copyright DKRZ licensed under CC BY-NC-SA 4.0
               (https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en)
-------------------------------------------------------------------------------
'''
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.colorbar as colorbar

def main():
    #-- define the colors for the colormap.
    cmap_rgb = [[0.997785, 0.999139, 0.846059],
                [0.910127, 0.964937, 0.695640],
                [0.769320, 0.909419, 0.706959],
                [0.521292, 0.812964, 0.731073],
                [0.304483, 0.732118, 0.761430],
                [0.141961, 0.597647, 0.756078],
                [0.122107, 0.483137, 0.712711],
                [0.131949, 0.382745, 0.665467],
                [0.138408, 0.297578, 0.624990],
                [0.031373, 0.113725, 0.345098]]
    
    #-- generate a listed colormap for plotting
    cmap = mcolors.ListedColormap(cmap_rgb)
    
    #-- define some levels and labels
    levels  =  [1, 2, 5, 10, 50, 100, 200, 500, 1000, 2000]
    labels  =  ['1','2','>5','>10','>50','>100','>200','>500','>1000','>2000']
    
    #-- create the plot
    plt.switch_backend('agg')

    fig = plt.figure(figsize=(10,3))
    cax = fig.add_axes([0.05, 0.5, 0.9, 0.08],        #-- [x, y, width, height]
                        autoscalex_on=True)
    cbar = colorbar.Colorbar(cax,
                                 orientation='horizontal',
                                 cmap=cmap,
                                 norm=plt.Normalize(-0.5, len(cmap_rgb) - 0.5))
    
    cbar.set_ticks(range(len(cmap_rgb)))
    cbar.ax.set_xticklabels(labels, fontsize=10)
    cbar.solids.set_edgecolor('black')
    cbar.set_label(label='Colorbar label', weight='bold', fontsize=14)
    
    plt.savefig('plot_colorbar_from_scratch.png', facecolor='white')
    

if __name__ == '__main__':
    main()

Plot result#

image0