Reputation: 331
I am trying to plot discrete values in a heatmap using seaborn. Here is the list I am trying to plot:
xa = [[5, 4, 4, 4, 13, 4, 4],
[1, 9, 4, 3, 9, 1, 4],
[4, 1, 7, 1, 5, 3, 7],
[1, 9, 4, 3, 9, 5, 4],
[2, 1, 4, 1, 9, 4, 3],
[9, 4, 8, 1, 7, 1, 9],
[4, 8, 1, 7, 1, 4, 8]]
Here is the code that I am using to plot the heatmaps:
import numpy as np
import seaborn as sns
from matplotlib.colors import ListedColormap
data = np.asarray(xa)
sns.heatmap( data,cmap=ListedColormap(['green', 'yellow', 'red']))
My question is how do I plot each number to a specific colour. The range of values will be from 1-17. So 17 different colours one for each number. I did read some other answers but none of them talked how to assign a number a specific value. Thanks!
Upvotes: 5
Views: 2536
Reputation: 12417
If I understood you correctly, you can do something like this:
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.colors as c
data = np.asarray(xa)
colors = {"white":1, "gray":2, "yellow":3, "lightgreen":4, "green":5, "lightblue":6, "blue":7, "lightcoral":8, "red":9, "brown":10,
"violet":11, "blueviolet":12, "indigo":13, "khaki":14, "orange":15, "pink":16, "black":17}
l_colors = sorted(colors, key=colors.get)
cMap = c.ListedColormap(l_colors)
fig, ax = plt.subplots()
ax.pcolor(data[::-1], cmap=cMap, vmin=1, vmax=len(colors))
# plt.axis('off') # if you don't want the axis
plt.show()
For each number corresponds a color, starting from 1 (white), 2 (gray), till 17 (black). As you can see there are no blacks in the image because there are no 17s in your array and the colormap is not normalized.
Or with seaborn
:
data = np.asarray(xa)
colors = {"white":1,"gray":2,"yellow":3,"lightgreen":4, "green":5, "lightblue":6, "blue":7, "lightcoral":8, "red":9, "brown":10,
"violet":11, "blueviolet":12,"indigo":13, "khaki":14, "orange":15, "pink":16, "black":17}
l_colors = sorted(colors, key=colors.get)
cMap = c.ListedColormap(l_colors)
sns.heatmap(data,cmap=l_colors, vmin=1, vmax=len(colors))
If you want all ticks on the legend, add this:
ax = sns.heatmap(data,cmap=l_colors, vmin=1, vmax=len(colors))
colorbar = ax.collections[0].colorbar
colorbar.set_ticks([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])
Upvotes: 4