Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib explicit value to colormap

Matplotlib does not support any simple way to define an explicit color map of the form:

my_map = {
    1: "green",
    2: "orange",
    3: "red"
}

I would have to use a custom colormap with normalization that just so happens to fall onto number 1, 2, 3 (which seems like way too complicated for something so simple…), right?

The only really simple approach I found was to use cmap = ListedColormap(['green', 'orange', 'red'], 'indexed'), which, however, will obviously break if not all numbers occur at least once, e.g. assuming the categorical data I want to plot comes as data = [2,2,2,2,2], but all will be mapped to green instead of orange.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As you say, this works:

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np

cmap = ListedColormap(['green', 'orange', 'red'], 'indexed')
data = np.random.randint(1, 4, size=(5, 5))
plt.imshow(data, cmap=cmap)
plt.colorbar()

And produces:

Output when all values present

But if you only have ones (say), the colourmap scales automatically. You could fix it with vmin and vmax:

data = np.ones((5, 5))
plt.imshow(data, cmap=cmap, vmin=1, vmax=3)
plt.colorbar()

It gives you:

The expected output

Which I think is the required output.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading