tsznxyz
tsznxyz

Reputation: 199

matplotlib heatmap with discrete values with custom defined colors

i'm trying to generate a heatmap with custom colors for each cell based on the values in Python.

data = [ [0,3,2,5],[2,3,3,0],...,[0,0,2,2]]
colors = {0:'red',2:'blue',3:'green',5:'purple'}

Anyone could help?

Upvotes: 3

Views: 873

Answers (1)

gg349
gg349

Reputation: 22701

This is a MWE of it working:

from matplotlib import colors
data = array([[1,2,3],[2,3,5], [3,1,2]])
cols = {1:'red',2:'blue',3:'green',5:'purple'}

cvr = colors.ColorConverter()
tmp = sorted(cols.keys())
cols_rgb = [cvr.to_rgb(cols[k]) for k in tmp]
intervals = array(tmp + [tmp[-1]+1]) - 0.5
cmap, norm = colors.from_levels_and_colors(intervals,cols_rgb)
plt.pcolor(data,cmap = cmap, norm = norm)

Here's the result:

enter image description here

Upvotes: 2

Related Questions