自定义颜色映射

2024-09-25 10:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用一个自定义颜色图绘制一个热图,尽管不完全是这样。在

enter image description here

我想要一张这样的彩色地图。在间隔[-0.6,0.6]中,颜色为浅灰色。高于0.6时,红色增强。低于-0.6另一种颜色,比如蓝色,会增强。在

如何使用python和matplotlib创建这样的colormap?

到目前为止我所拥有的: 在seaborn中有一个命令seaborn.diverging_palette(220, 10, as_cmap=True),它生成一个从蓝光到灰红色的颜色映射。但与[-0.6,0.6]仍然没有差距。在

enter image description here


Tags: 命令间隔matplotlib颜色地图绘制seaborn彩色
1条回答
网友
1楼 · 发布于 2024-09-25 10:33:48

颜色贴图在0..1范围内规格化。所以如果你的数据限制是-1..1,-0.6将规范化为0.2,+0.6将规范化为0.8。在

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors

norm = matplotlib.colors.Normalize(-1,1)
colors = [[norm(-1.0), "darkblue"],
          [norm(-0.6), "lightgrey"],
          [norm( 0.6), "lightgrey"],
          [norm( 1.0), "red"]]

cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", colors)


fig, ax=plt.subplots()
x = np.arange(10)
y = np.linspace(-1,1,10)
sc = ax.scatter(x,y, c=y, norm=norm, cmap=cmap)
fig.colorbar(sc, orientation="horizontal")
plt.show()

enter image description here

相关问题 更多 >