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: Imshow with 1 color for each discrete value

I have a 2d array, which contains integer values 1 – 7. I want to plot the array out with 1 color for each discrete value.

fig, ax = plt.subplots()
cmap = mpl.cm.get_cmap('Set2', 7)
im = plt.imshow(data, cmap=cmap, vmin=1, vmax=7, aspect=25, interpolation=None)
fig.colorbar(im, ticks=range(7), orientation="horizontal")

I can’t seem to get the colors correct. As seen below, the tick marks isn’t at the middle of the color. Also, I don’t know why I’m getting more than 2 colors for some columns, for e.g. at the x=300 point, there is a small orange line between the light green and green-blue. The data is 2 x 660, so each column should have at max 2 distinct values.

enter image description here

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 :

To fix the colorbar you can expand the color range by 0.5 in both directions:

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

data = np.random.randint(1, 8, (10, 10))

fig, ax = plt.subplots()
cmap = mpl.cm.get_cmap('Set2', 7)
im = plt.imshow(data, cmap=cmap, vmin=0.5, vmax=7.5, aspect=1, interpolation="none")
fig.colorbar(im, ticks=range(8), orientation="horizontal")

enter image description here

… or look into tick locators.

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