简体   繁体   English

在seaborn中自定义颜色条 - 热图

[英]Customizing color bar in seaborn - heatmap

I have a heatmap to represent discrete values.我有一个热图来表示离散值。

import seaborn as sns
import pandas as pd

data = np.array([[2, 1, 1, 1, 2, 3, 3, 3, 3, 3],
                 [3, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],])

x_labels = ['a', 'b', 'c', 'd']

dataFrame = pd.DataFrame(data.T)

#get discrete colormap
cmap = colors.ListedColormap(['blue','red','black','yellow'])

ax = sns.heatmap(dataFrame, cmap=cmap, linewidths=.5, linecolor='lightgray')
ax.set_xticklabels(x_labels)
ax.set_yticklabels(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])

# Manually specify colorbar labelling after it's been generated
colorbar = ax.collections[0].colorbar
colorbar.set_ticks([1.3, 1.7, 2.2, 2.7])
colorbar.set_ticklabels(['A', 'B', 'C', 'NA'])

plt.show()

在此处输入图片说明 在此处输入图片说明

How can I specifiy those colors in a way to represent colors = {1: 'A', 2: 'B', 3: 'C', 4: 'NA'} in data如何在数据中指定这些颜色来表示颜色 = {1: 'A', 2: 'B', 3: 'C', 4: 'NA'}

It follows the order you give.它遵循您给出的命令。 Since your code has由于您的代码有

cmap = ListedColormap(['red','black','yellow', 'blue'])
colorbar.set_ticklabels(['A', 'B', 'C', 'NA'])

The colors are mapped to these categories.颜色映射到这些类别。 Change the order to, say, ['red','black', 'blue','yellow'] and the labels will change accordingly.将顺序更改为,例如, ['red','black', 'blue','yellow']标签将相应更改。

By default, the colormaps are scaled to the range of your data.默认情况下,颜色图会缩放到您的数据范围。 In your case, your data is [1-3], so matplotlib is scaling your four-color colormap to that range.在您的情况下,您的数据是 [1-3],因此 matplotlib 将您的四色颜色图缩放到该范围。

Since you, in fact, want to scale the colormap to the range [1-4], you'll have to use the arguments vmin= and vmax= to tell the system what range of data to use.由于您实际上想要将颜色图缩放到范围 [1-4],您必须使用参数vmin=vmax=来告诉系统要使用的数据范围。

ax = sns.heatmap(dataFrame, cmap=cmap, linewidths=.5, linecolor='lightgray', vmin=1, vmax=4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM