如何将Disrerte值映射到海运中的热图?
问题描述
我正在尝试使用Seborn绘制热图中的离散值。以下是我试图绘制的列表:
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]]
以下是我用来绘制热图的代码:
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']))
我的问题是如何将每个数字绘制成特定的颜色。取值范围为1-17。所以有17种不同的颜色,每个数字一种。我读了一些其他的答案,但没有一个谈到如何给一个数字赋一个特定值。谢谢!
解决方案
如果我理解正确,您可以这样做:
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()
每个数字对应一种颜色,从1(白色)、2(灰色)到17(黑色)。如您所见,图像中没有黑色,因为您的数组中没有17,并且色彩映射表未标准化。
或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))
如果您想要图例上的所有刻度,请添加以下内容:
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])
相关文章