Unsure if it is possible to leverage matplotlib’s DivergingNorm for color maps under the framework of pandas Styler objects. As an example:
JavaScript
x
12
12
1
import pandas as pd
2
import matplotlib.cm
3
4
# retrieve red-yellow-green diverging color map
5
cmap = matplotlib.cm.get_cmap('RdYlGn')
6
7
# create sample pd.DataFrame
8
ix = pd.date_range(start=pd.Timestamp(2020, 1, 1), periods=4)
9
df = pd.DataFrame(index=ix, columns=['D/D CHANGE'], data=[-1, 0, 2, 5])
10
11
df.style.background_gradient(cmap=cmap)
12
Ideally only negative (positive) values would appear red (green).
Advertisement
Answer
It doesn’t look like there is an option to pass a custom normalization to background_gradient
(maybe could be a feature request to post on pandas github). But you can use a custom function to get the desired result:
JavaScript
1
11
11
1
def background_with_norm(s):
2
cmap = matplotlib.cm.get_cmap('RdYlGn')
3
norm = matplotlib.colors.DivergingNorm(vmin=s.values.min(), vcenter=0, vmax=s.values.max())
4
return ['background-color: {:s}'.format(matplotlib.colors.to_hex(c.flatten())) for c in cmap(norm(s.values))]
5
6
# create sample pd.DataFrame
7
ix = pd.date_range(start=pd.Timestamp(2020, 1, 1), periods=4)
8
df = pd.DataFrame(index=ix, columns=['D/D CHANGE'], data=[-1, 0, 2, 5])
9
10
df.style.apply(background_with_norm)
11