自定义色彩图 [英] Custom Colormap
问题描述
我想绘制一个具有与此相似的自定义颜色图的热图,尽管不完全一样.
I want to plot a heatmap with a custom colormap similar to this one, although not exactly.
我想要一个像这样的色彩图.在区间 [-0.6, 0.6] 中,颜色为浅灰色.高于 0.6,红色变深.低于-0.6时,另一种颜色(例如蓝色)会增强.
I'd like to have a colormap that goes like this. In the interval [-0.6, 0.6] the color is light grey. Above 0.6, the color red intensifies. Below -0.6 another color, say blue, intensifies.
如何使用python和matplotlib创建这样的颜色图?
到目前为止我所拥有的:在 seaborn
中,有一个命令 seaborn.diverging_palette(220,10,as_cmap = True)
会生成一个从蓝灰色到红色的颜色表.但是与[-0.6,0.6]之间仍然没有差距.
What I have so far:
In seaborn
there is the command seaborn.diverging_palette(220, 10, as_cmap=True)
which produces a colormap going from blue-light grey-red. But there is still no gap from [-0.6, 0.6].
推荐答案
色图在0..1范围内进行了归一化.因此,如果您的数据限制为 -1..1,则 -0.6 将标准化为 0.2,+0.6 将标准化为 0.8.
Colormaps are normalized in the 0..1 range. So if your data limits are -1..1, -0.6 would be normalized to 0.2, +0.6 would be normalized to 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()
这篇关于自定义色彩图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!