Home > Back-end >  Matplotlib: Imshow with 1 color for each discrete value
Matplotlib: Imshow with 1 color for each discrete value

Time:11-17

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

CodePudding user response:

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.

  • Related