seaborn 热图颜色图

时间:2021-01-08 20:51:53

标签: python pandas numpy seaborn

我有一个数据框 df,其值从 0 到 x(x 是整数,没有固定值),在我的例子中是 x=10

我想用 cmap 'Reds' 映射热图,但是值 0 不应该是白色而是绿色 '#009933'

import seaborn as sns # matplotlib inline 
import random
data = []
for i in range(10):
    data.append([random.randrange(0, 11, 1) for _ in range(10)])
df = pd.DataFrame(data)

fig, ax = plt.subplots(figsize = (12, 10)) 
# cmap = [????]
ax = sns.heatmap(df, cmap='Reds', linewidths = 0.005, annot = True, cbar=True) 
                            
plt.show()

enter image description here 我该怎么做?

2 个答案:

答案 0 :(得分:3)

作为 accepted answer 的替代方案,您还可以将 vmin 设置为略高于 0,并使用 set_under 定义超出范围值的颜色:

import copy
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

cmap = copy.copy(plt.get_cmap("Reds"))
cmap.set_under('#009933')
sns.heatmap(np.random.randint(0,10,(10,10)), cmap=cmap, lw=0.005, annot=True, vmin=1e-5)

enter image description here

默认情况下,颜色栏中不显示 under 颜色。要更改颜色条,请使用例如 sns.heatmap(..., cbar_kws={'extend':'min', 'extendrect':True})。这些参数的解释可以在colorbar docs中找到。

答案 1 :(得分:2)

您可以使用 LinearSegmentedColormap 中的 matplotlib.colors。您首先必须找到最大值,在本例中为 10,然后使用它来创建一个以绿色开头的颜色变量,然后转到标准的“红色”颜色集。另外,在用seaborn制作热图时将colorbar设为False,用matplotlib单独制作一张。

此代码改编自here

import matplotlib.pyplot as plt
import matplotlib.colors as cl
import seaborn as sns
import pandas as pd
import numpy as np
import random

data = []
for i in range(10):
    data.append([random.randrange(0, 11, 1) for _ in range(10)])
df = pd.DataFrame(data)

fig, ax = plt.subplots(figsize = (12, 10)) 
cmap_reds = plt.get_cmap('Reds')
num_colors = 11
colors = ['#009933'] + [cmap_reds(i / num_colors) for i in range(1, num_colors)]
cmap = cl.LinearSegmentedColormap.from_list('', colors, num_colors)
ax = sns.heatmap(df, cmap=cmap, vmin=0, vmax=num_colors, square=True, cbar=False, annot = True)
cbar = plt.colorbar(ax.collections[0], ticks=range(num_colors + 1))
cbar.set_ticks(np.linspace(0, num_colors, 2*num_colors+1)[1::2])
cbar.ax.set_yticklabels(range(num_colors))
plt.show()

这是输出: enter image description here