13

This code enables me to plot a colormap of a "3d" array [X,Y,Z] (they are 3 simple np.array of elements). But I can't succeed in adding a vertical written label at the right of the colorbar legend.

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure("Color MAP 2D+")

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Color MAP 2D+")

#Legend
def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)
import matplotlib.ticker as ticker
plt.colorbar(contour, format=ticker.FuncFormatter(fmt))

plt.show()

enter image description here

It's anoying to not get an easy answer from google... can someone help me ?

Agape Gal'lo
  • 687
  • 4
  • 9
  • 23

2 Answers2

19

You are looking to add a label to the colorbar object. Thankfully, colorbar has a set_label function.

in short:

cbar = plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
cbar.set_label('your label here')

In a minimal script:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

X = np.random.uniform(-2, 2, 200)
Y = np.random.uniform(-2, 2, 200)
Z = X*np.exp(-X**2 - Y**2)

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)

cbar = plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
cbar.set_label('your label here')

plt.show()

enter image description here

tmdavison
  • 64,360
  • 12
  • 187
  • 165
  • I have an additional question: how can you change the size of the numbers, on the right of the colorbar ? @tom – Agape Gal'lo Oct 14 '18 at 21:23
  • 1
    @AgapeGal'lo LMGTFY: https://stackoverflow.com/questions/15305737/python-matplotlib-decrease-size-of-colorbar-labels In short: `cbar.ax.tick_params(labelsize=20)` – tmdavison Oct 15 '18 at 08:28
0

I believe your code is working. See this example:

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

iris = datasets.load_iris().data
X = iris[:,0]
Y = iris[:,1]
Z = iris[:,2]

fig = plt.figure("Color MAP 2D+")

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Color MAP 2D+")

#Legend
def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)

import matplotlib.ticker as ticker
plt.colorbar(contour, format=ticker.FuncFormatter(fmt))

plt.show()

Output:

enter image description here

Scott Boston
  • 147,308
  • 15
  • 139
  • 187