问题描述
我有以下数据框:
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)
看起来像这样:
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:
- 值< 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])
会产生以下情节:
什么是正确的方法?
推荐答案
要获得渐变色,可以执行以下操作:
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()
在这里,我已经设置了vmin
和vmax
,以使它们等距大约是1.0的白色值,我认为这意味着任何高于2.0的值都不会比这些值更暗在2.0.选择更大的范围可能会得到更好的结果范围,即使这表示比例包括负数值,例如vmin=-2, vmax=4
.
Here I've set vmin
and vmax
so that they're equally spacedaround the white value at 1.0, unfortunately I think this meansthat any values above 2.0 don't become any darker than thoseat 2.0. You may get better results by choosing a widerrange, even if this means the scale includes negativevalues, e.g. vmin=-2, vmax=4
.
这篇关于如何通过 pandas 数据框在Matplotlib热图中创建预定义的颜色范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!