1

I would like to make a heatmap for a matrix of data such that all positions that are 1 will be red, all positions that are 2 will be white, and etc. with an arbitrary specification. Ideally this should handle the case where all of the values are the same, plotting just a uniform color.

The best solution I have come up with is using:

from matplotlib import colors
import matplotlib.pyplot as plt
import numpy as np
cmap = colors.ListedColormap(['white', 'blue', 'red', 'purple'])
data = np.array([[0, 0,0,0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]])
plt.imshow(data, interpolation='none', aspect='auto', origin='upper', cmap=cmap)

which successfully prints a stripe of each color. However, if I plot instead:

dat2 = np.array([[0, 0,0,0], [1, 1, 1, 1]])
plt.imshow(dat2, interpolation='none', aspect='auto', origin='upper', cmap=cmap)

instead, it plots white and purple rather than white and blue. If the data contains only one of the numbers, it will only plot white.

1 Answer 1

5

I believe the colormap is renormalizing to your data. Passing values that range from 0 to 1 gives a colormapping of white:0, blue:0.333, red:0.666, purple:1.0.

You can prevent this behavior by passing vmin and vmax to the plot.

plt.imshow(dat2, interpolation='none', aspect='auto', origin='upper',
           cmap=cmap, vmin=0, vmax=4)

(I don't have python running on my computer right now, so I am unable to test this.)

Sign up to request clarification or add additional context in comments.

2 Comments

This is helpful, thanks. I am making a wrapper function which automatically sets vmin=0 and vmax=len(cmap.colors)
That will work if your array values are always 0 to len(cmap.colors) as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.