Exemples de comment personnaliser les labels de la colorbar avec imshow de matplotib:
Colorbar de départ
Tracer une simple colorbar avec matplotlib:

import numpy as npimport matplotlib.pyplot as pltdef f(x,y):return (x+y)*np.exp(-5.0*(x**2+y**2))x,y = np.mgrid[-1:1:100j, -1:1:100j]z = f(x,y)plt.imshow(z,extent=[-1,1,-1,1])plt.colorbar()plt.savefig("ImshowColorBar01.png")plt.show()
Modifier la taille des labels
Pour modifier la taille des labels on peut utiliser l'option labelsize, exemple diminuer la taille des labels labelsize=7:

import numpy as npimport matplotlib.pyplot as pltdef f(x,y):return (x+y)*np.exp(-5.0*(x**2+y**2))x,y = np.mgrid[-1:1:100j, -1:1:100j]z = f(x,y)plt.imshow(z,extent=[-1,1,-1,1])cb = plt.colorbar()cb.ax.tick_params(labelsize=7)plt.savefig("ImshowColorBar02.png")plt.show()
Modifier la position des labels
Pour modifier la position des labels on peut utiliser l'argument ticks, exemple

import numpy as npimport matplotlib.pyplot as pltdef f(x,y):return (x+y)*np.exp(-5.0*(x**2+y**2))x,y = np.mgrid[-1:1:100j, -1:1:100j]z = f(x,y)plt.imshow(z,extent=[-1,1,-1,1],vmin=z.min(),vmax=z.max())v1 = np.linspace(z.min(), z.max(), 8, endpoint=True)cb = plt.colorbar(ticks=v1)plt.savefig("ImshowColorBar03.png")plt.show()
Modifier le format des labels
On peut aussi changer le format des labels:

import numpy as npimport matplotlib.pyplot as pltdef f(x,y):return (x+y)*np.exp(-5.0*(x**2+y**2))x,y = np.mgrid[-1:1:100j, -1:1:100j]z = f(x,y)f = plt.figure()ax = f.add_subplot(111)plt.imshow(z,extent=[-1,1,-1,1],vmin=z.min(),vmax=z.max())v1 = np.linspace(z.min(), z.max(), 8, endpoint=True)cb = plt.colorbar(ticks=v1)cb.ax.set_yticklabels(["{:4.2f}".format(i) for i in v1])plt.savefig("ImshowColorBar04.png")
Références
| Liens | Site |
|---|---|
| Python/Matplotlib - Colorbar Range and Display Values | stackoverflow |
| Truncating floats in Python | stackoverflow |
| Setting the limits on a colorbar in matplotlib | stackoverflow |
| color example code: colormaps_reference.py | stackoverflow |
| api example code: colorbar_only.py | matplotlib doc |
| matplotlib: limits when using plot and imshow in same axes | stackoverflow |
| How to format a floating number to fixed width in Python | stackoverflow |
| matplotlib: colorbars and it's text labels | stackoverflow |
| Matplotlib colorbar background and label placement | stackoverflow |
