将 pd.DataFrame Styler 对象的背景渐变色图居中
Centering a background gradient color map for a pd.DataFrame Styler object
不确定是否可以在 pandas Styler 对象的框架下利用 matplotlib 的 DivergingNorm for color maps。例如:
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)
理想情况下只有负(正)值会显示为红色(绿色)。
似乎没有将自定义规范化传递给 background_gradient
的选项(可能是 pandas github 上对 post 的功能请求).但是您可以使用自定义函数来获得所需的结果:
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)
不确定是否可以在 pandas Styler 对象的框架下利用 matplotlib 的 DivergingNorm for color maps。例如:
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)
理想情况下只有负(正)值会显示为红色(绿色)。
似乎没有将自定义规范化传递给 background_gradient
的选项(可能是 pandas github 上对 post 的功能请求).但是您可以使用自定义函数来获得所需的结果:
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)