[英]Custom color palette intervals in seaborn heatmap
我正在尝试使用 seaborn 库绘制热图。
绘图函数如下所示:
def plot_confusion_matrix(data, labels, **kwargs):
"""Visualize confusion matrix as a heat map."""
col_map = kwargs.get('color_palette', sns.light_palette('navy', n_colors=5, as_cmap=False))
sns.heatmap(
vmin=0.0,
vmax=1.0,
data=data,
cmap=col_map,
xticklabels=labels,
yticklabels=labels,
linewidths=0.75,
)
现在我正在努力解决的问题是 seaborn 热图(查看波纹管)均匀地分割色标,因此大多数数据具有相同的颜色(因为数据分布不均匀)。
我无法找到如何为颜色级别设置某种间隔或边界。
假设我有以下十六进制颜色值数组:
['#e5e5ff', '#acacdf', '#7272bf', '#39399f', '#000080']
有没有办法设置颜色,例如
[(threshold_0, hex_0), (threshold_1, hex_1), ..., (threshold_n, hex_n)]
其中threshold_i
是 [0, 1) 范围内的值
感谢任何帮助。
PS:用于说明的当前热图:
关于此处的文档,您可以创建自己的颜色词典。 这些 dicts 必须是 rgb 值,所以我写了第一个测试函数来从 Hex_colors 和你想要的阈值生成一个:
def NonLinCdict(steps, hexcol_array):
cdict = {'red': (), 'green': (), 'blue': ()}
for s, hexcol in zip(steps, hexcol_array):
rgb =matplotlib.colors.hex2color(hexcol)
cdict['red'] = cdict['red'] + ((s, rgb[0], rgb[0]),)
cdict['green'] = cdict['green'] + ((s, rgb[1], rgb[1]),)
cdict['blue'] = cdict['blue'] + ((s, rgb[2], rgb[2]),)
return cdict
hc = ['#e5e5ff', '#acacdf', '#7272bf', '#39399f', '#000080']
th = [0, 0.1, 0.5, 0.9, 1]
cdict = NonLinCdict(th, hc)
cm = mc.LinearSegmentedColormap('test', cdict)
plt.figure()
sns.heatmap(
vmin=0.0,
vmax=1.0,
data=data,
cmap=cm,
linewidths=0.75)
它产生:
还可以做更多的事情(例如,针对离散跳转,只需查看文档...)但这应该可以回答您的原始问题-这次包括“自定义”...
但是,我必须补充一下我的个人意见:像这样拉伸的颜色图在这里可能会“令人愉悦”,但应该注意它们不会误导观众的眼睛。
我希望这有帮助。
我能够找到(在我看来不是很干净)解决方案,它使用matplotlib.colors.LinearSegmentedColormap
。
代码如下所示:
# NOTE: jupyter notebook mode
%matplotlib inline
import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap
boundaries = [0.0, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0] # custom boundaries
# here I generated twice as many colors,
# so that I could prune the boundaries more clearly
hex_colors = sns.light_palette('navy', n_colors=len(boundaries) * 2 + 2, as_cmap=False).as_hex()
hex_colors = [hex_colors[i] for i in range(0, len(hex_colors), 2)]
colors=list(zip(boundaries, hex_colors))
custom_color_map = LinearSegmentedColormap.from_list(
name='custom_navy',
colors=colors,
)
sns.heatmap(
vmin=0.0,
vmax=1.0,
data=data,
cmap=custom_color_map,
xticklabels=labels,
yticklabels=labels,
linewidths=0.75,
)
故意不解决您的问题中的“习惯” - 也许这在此期间有所帮助:
在众所周知的在整个范围内平滑变化的颜色图下面,还有一些更适合显示多个数据带中的微小差异,例如gist_ncar
。
另见https://matplotlib.org/examples/color/colormaps_reference.html
创建于
sns.heatmap(vmin=0.0, vmax=1.0, data=data, cmap='gist_ncar', linewidths=0.75)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.