如何从 Pandas 数据帧在 Matplotlib 热图中创建预定义的颜色范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29138951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create predefined color range in Matplotlib heat map from a Pandas Dataframe
提问by neversaint
I have the following data frame:
我有以下数据框:
import pandas as pd
Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
data= [[ 1, 0.3, 2.1, 1.3],[ 2.5, 1, 1, 0.77],[ 0.0, 1, 2, 1],[ 0, 3.2, 1, 1.2],[ 10, 1, 1, 1]]
df = pd.DataFrame(data, index=Index, columns=Cols)
That looks like this:
看起来像这样:
In [25]: df
Out[25]:
A B C D
aaa 1.0 0.3 2.1 1.30
bbb 2.5 1.0 1.0 0.77
ccc 0.0 1.0 2.0 1.00
ddd 0.0 3.2 1.0 1.20
eee 10.0 1.0 1.0 1.00
What I want to do is to create a heat map with the following condition:
我想要做的是创建一个具有以下条件的热图:
- Value < 1 : Blue
- Value == 1 : White
- 1 < Value < 2: Light Red
- Value >=2 : Dark red
- 值 < 1:蓝色
- 值 == 1:白色
- 1 < 值 < 2:浅红色
- 值 >=2 : 深红色
Ideally the color would have to be in gradation. This is my failed poor attempt:
理想情况下,颜色必须是渐变的。这是我失败的糟糕尝试:
from matplotlib import colors
cmap = colors.ListedColormap(['darkblue','blue','white','pink','red'])
bounds=[-0.5, 0.5, 1.5, 2.5, 3.5]
norm = colors.BoundaryNorm(bounds, cmap.N)
heatmap = plt.pcolor(np.array(data), cmap=cmap, norm=norm)
plt.colorbar(heatmap, ticks=[0, 1, 2, 3])
Which produce this plot:
产生这个情节:


What's the right way to do it?
正确的做法是什么?
回答by Marius
To get gradiated colours you can do:
要获得渐变颜色,您可以执行以下操作:
import matplotlib.pyplot as plt
# Builtin colourmap "seismic" has the blue-white-red
# scale you want
plt.pcolor(np.array(data), cmap=plt.cm.seismic, vmin=0, vmax=2)
plt.colorbar()
plt.show()
Here I've set vminand vmaxso that they're equally spaced
around the white value at 1.0, unfortunately I think this means
that any values above 2.0 don't become any darker than those
at 2.0. You may get better results by choosing a wider
range, even if this means the scale includes negative
values, e.g. vmin=-2, vmax=4.
在这里,我已经设置vmin并vmax让他们周围的白色值在1.0等距,不幸的是,我认为,这意味着在2.0以上的任何值不会变得比在2.0任何暗。通过选择更宽的范围,您可能会获得更好的结果,即使这意味着比例包含负值,例如vmin=-2, vmax=4。



