How to split the color bar into sets and label them

I want to replicate such beauty, any suggestions?
IMG_20220330_213413

I used contourf and drawedges=True to get the divided colorbar.
To get the colorbar in it’s own box, I would suggest using ax.inset_axes.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, np.pi, 100)
y = np.linspace(0, np.pi, 100)
z = np.cos(x[None,:]) + np.cos(y[:,None])
levels = np.linspace(-0.7, 1.3, 11)

fig, ax = plt.subplots()
CS = ax.contourf(x, y, z, levels=levels, cmap='terrain')
cbar = fig.colorbar(CS, ax=ax, drawedges=True)
cbar.set_ticks([-0.6, 0, 0.6, 1.2])
cbar.ax.set_ylim(1.3, -0.7)
cbar.ax.set_title('Range (inches)')
cbar.outline.set_edgecolor('w')
cbar.dividers.set_edgecolor('w')
cbar.dividers.set_linewidth(0.8)
plt.show()

2 Likes

@emascot that’s a great answer. however, do you know any trick for the arrow part and the uplift subsidence annotations in colorbar?

@aminevsaziz the arrow part can be done with annotate. I had a problem annotating the colorbar axis so I had to put the colorbar in its own axis and align the zero manually.

fig, ax = plt.subplots()
CS = ax.contourf(x, y, z, levels=levels, cmap='terrain')

inset = ax.inset_axes([0.8, 0.3, 0.4, 0.8])
inset.set_xlim(-1, 1)
inset.set_ylim(1.55, -0.95)
inset.set_xticks([])
inset.set_yticks([])
inset.plot([-0.75, 0], [0, 0], 'k', linewidth=0.8)
inset.annotate('Uplift', (-0.5, 0), (-0.5, -0.6), arrowprops={'arrowstyle':'<-'}, ha='center')
inset.annotate('Subsidence', (-0.5, 0), (-0.5, 0.6), arrowprops={'arrowstyle':'<-'}, ha='center')
inset.text(0, -0.8, 'Range (inches)', ha='center')

cax = inset.inset_axes([0.5, 0.1, 0.25, 0.8])
cbar = fig.colorbar(CS, cax=cax, drawedges=True)
cbar.set_ticks([-0.6, 0, 0.6, 1.2])
cbar.ax.set_ylim(1.3, -0.7)
cbar.outline.set_edgecolor('w')
cbar.dividers.set_edgecolor('w')
cbar.dividers.set_linewidth(0.8)
plt.show()

Another way you could make this is to manually create a colorbar using PolyCollection. This would make it easier to align the annotations to the colorbar, but would make it more tedious to make the colorbar.

1 Like