Search code examples
python-3.xmatplotlibcolorbarcolormap

Plotting colorbar in Python 3


I am trying to color the errorbar points based on the color from an array. But getting an error. My code is shown below:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable, coolwarm as cmap
from matplotlib.colors import Normalize

fig = plt.figure(1)
sp = fig.add_subplot(1, 1, 1)
sp.set_xlabel(r'$x$')
sp.set_ylabel(r'$y$')

x = np.random.rand(10)
y = np.random.rand(10)
M = np.logspace(9, 10, 10)
norm = Normalize(vmin=8, vmax=11,clip=False)  # controls the min and max of the colorbar
smap = ScalarMappable(cmap=cmap, norm=norm)
for xi, yi, Mi in zip(x, y, M):
    c = cmap(norm(np.log10(Mi)))  # make sure to color by log of mass, not mass
    sp.errorbar(
        xi,
        yi,
        yerr=[[.1], [.1]],
        xerr=[[.1], [.1]],
        ecolor=c,
        marker='o',
        mec=c,
        mfc=c
    )

cb = plt.colorbar(smap)
cb.set_label(r'$\log_{10}M$')

I am getting the following error: TypeError: You must first set_array for mappable


Solution

  • For matplotlib < 3.1, you need to set an array - which can be empty

    sm = ScalarMappable(cmap=cmap, norm=norm)
    sm.set_array([])
    fig.colorbar(sm)
    

    For matplotlib >= 3.1, this is not necessary any more.

    sm = ScalarMappable(cmap=cmap, norm=norm)
    fig.colorbar(sm)