How to change colorbar labels in matplotlib ?

Published: March 24, 2019

DMCA.com Protection Status

Examples of how to change colorbar labels in matplotlib:

Simple Colorbar with colorbar

Plot a simple colorbar with matplotlib:

How to change colorbar labels in matplotlib ?
How to change colorbar labels in matplotlib ?

import numpy as np
import matplotlib.pyplot as plt

def 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()

Change labels font size

To change the size of labels, there is the option labelsize, example:

How to change colorbar labels in matplotlib ?
How to change colorbar labels in matplotlib ?

import numpy as np
import matplotlib.pyplot as plt

def 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

To change the labels position:

How to change colorbar labels in matplotlib ?
How to change colorbar labels in matplotlib ?

import numpy as np
import matplotlib.pyplot as plt

def 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

To change the format:

How to change colorbar labels in matplotlib ?
How to change colorbar labels in matplotlib ?

import numpy as np
import matplotlib.pyplot as plt

def 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")

References

Image

of