4

不确定是否可以在 pandas Styler 对象的框架下将 matplotlib 的DivergingNorm 用于颜色图。举个例子:

import pandas as pd
import matplotlib.cm

# retrieve red-yellow-green diverging color map
cmap = matplotlib.cm.get_cmap('RdYlGn')

# create sample pd.DataFrame
ix = pd.date_range(start=pd.Timestamp(2020, 1, 1), periods=4)
df = pd.DataFrame(index=ix, columns=['D/D CHANGE'], data=[-1, 0, 2, 5])

df.style.background_gradient(cmap=cmap)

在此处输入图像描述

理想情况下,只有负(正)值会显示为红色(绿色)。

4

1 回答 1

4

看起来没有将自定义规范化传递给的选项background_gradient(可能是在 pandas github 上发布的功能请求)。但是您可以使用自定义函数来获得所需的结果:

def background_with_norm(s):
    cmap = matplotlib.cm.get_cmap('RdYlGn')
    norm = matplotlib.colors.DivergingNorm(vmin=s.values.min(), vcenter=0, vmax=s.values.max())
    return ['background-color: {:s}'.format(matplotlib.colors.to_hex(c.flatten())) for c in cmap(norm(s.values))]

# create sample pd.DataFrame
ix = pd.date_range(start=pd.Timestamp(2020, 1, 1), periods=4)
df = pd.DataFrame(index=ix, columns=['D/D CHANGE'], data=[-1, 0, 2, 5])

df.style.apply(background_with_norm)

在此处输入图像描述

于 2020-03-12T12:59:17.170 回答