[英]seaborn heatmap color map
I have a dataframe df
with values from 0 to x (x is integer and no fixed value), in my example is x=10我有一个 dataframe
df
,其值从 0 到 x(x 是 integer 并且没有固定值),在我的示例中是 x=10
I want to map the heatmap with cmap 'Reds', however where value 0 is should not be white but green '#009933'我想用 cmap 'Reds' map 热图,但是值 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()
As an alternative to the accepted answer you could also set vmin
to slightly above 0
and define the color for out-of-range values with set_under
:作为已接受答案的替代方案,您还可以将
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)
The under
-color is not shown by default in the colorbar.底色默认情况下不显示
under
颜色栏中。 To alter the colorbar, use for example sns.heatmap(..., cbar_kws={'extend':'min', 'extendrect':True})
.要更改颜色条,请使用例如
sns.heatmap(..., cbar_kws={'extend':'min', 'extendrect':True})
。 The explanation of these parameters can be found in the colorbar docs .这些参数的解释可以在colorbar docs中找到。
You can use a LinearSegmentedColormap
from matplotlib.colors
.您可以使用
LinearSegmentedColormap
中的matplotlib.colors
。 You first have to find the largest value, in this case 10, then use that to create a colors variable that starts with green, then goes to the standard 'Reds' colorset.您首先必须找到最大值,在本例中为 10,然后使用它创建一个以绿色开头的 colors 变量,然后转到标准的“红色”颜色集。 Also, set the colorbar to False when making the heatmap with seaborn, and separately make one with matplotlib.
另外,使用 seaborn 制作热图时将颜色栏设置为 False,并单独使用 matplotlib 制作一张。
This code was adapted from 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.