【问题标题】:Customizing color bar in seaborn - heatmap在 seaborn 中自定义颜色条 - 热图
【发布时间】:2020-06-21 02:49:16
【问题描述】:

我有一个热图来表示离散值。

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()

如何指定这些颜色以表示颜色 = {1: 'A', 2: 'B', 3: 'C', 4: 'NA'} in data

【问题讨论】:

    标签: python pandas dataframe seaborn heatmap


    【解决方案1】:

    它遵循您给出的命令。因为你的代码有

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

    颜色映射到这些类别。将顺序更改为['red','black', 'blue','yellow'],标签将相应更改。

    【讨论】:

      【解决方案2】:

      默认情况下,颜色图会根据您的数据范围进行缩放。在您的情况下,您的数据是 [1-3],因此 matplotlib 将您的四色颜色图缩放到该范围。

      由于您实际上想要将颜色图缩放到范围 [1-4],因此您必须 use the arguments vmin= and vmax= 告诉系统要使用的数据范围。

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

      【讨论】:

        猜你喜欢
        • 2021-07-06
        • 2020-10-21
        • 2021-09-16
        • 1970-01-01
        • 1970-01-01
        • 2018-07-13
        • 2018-05-07
        • 1970-01-01
        • 2020-09-28
        相关资源
        最近更新 更多