Home > OS >  Colorbar adjustment in heatmap using matplotlib
Colorbar adjustment in heatmap using matplotlib

Time:07-05

I am generating a heatmap based on array T. However, there is one value (1e-9) which is much lower than the rest (ignoring NaN). How do I adjust the colorbar so that I can see the minor changes in the remaining values of the array and also including 1e-9?

import numpy as np
from numpy import NaN
import matplotlib
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt


T=np.array([[6.19314835e 02, 6.19229656e 02, 6.19220233e 02],
       [6.14626547e 02, 6.18217141e 02, 6.19029892e 02],
       [1.00000000e-09,            NaN,            NaN]])

fig, ax = plt.subplots()
im = ax.imshow(T)

divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

enter image description here

CodePudding user response:

You can use vmin and vmax to set a range for the color map. The extreme low values can be indicated via a 'lower' color in the color map together with extend='min' in the colorbar.

import numpy as np
import matplotlib.pyplot as plt

T = np.array([[6.19314835e 02, 6.19229656e 02, 6.19220233e 02],
              [6.14626547e 02, 6.18217141e 02, 6.19029892e 02],
              [1.00000000e-09, np.NaN, np.NaN]])

cmap = plt.get_cmap('viridis').copy()
cmap.set_under('red')
vmin = np.nanmin(T[T>1e-8])
vmax = np.nanmax(T)
fig, ax = plt.subplots()
im = ax.imshow(T, cmap=cmap, vmin=vmin, vmax=vmax)
plt.colorbar(im, ax=ax,extend='min')
plt.tight_layout()
plt.show()

limiting the color range and setting an under color

  • Related