Skip to content

ENH: Add support for tablewise application of style.background_gradient with axis=None #21259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,7 @@ Other

- :meth: `~pandas.io.formats.style.Styler.background_gradient` now takes a ``text_color_threshold`` parameter to automatically lighten the text color based on the luminance of the background color. This improves readability with dark background colors without the need to limit the background colormap range. (:issue:`21258`)
- Require at least 0.28.2 version of ``cython`` to support read-only memoryviews (:issue:`21688`)
- :meth: `~pandas.io.formats.style.Styler.background_gradient` now also supports tablewise application (in addition to rowwise and columnwise) with ``axis=None`` (:issue:`15204`)
-
-
-
57 changes: 33 additions & 24 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -913,21 +913,22 @@ def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0,
def _background_gradient(s, cmap='PuBu', low=0, high=0,
text_color_threshold=0.408):
"""Color background in a range according to the data."""
if (not isinstance(text_color_threshold, (float, int)) or
not 0 <= text_color_threshold <= 1):
msg = "`text_color_threshold` must be a value from 0 to 1."
raise ValueError(msg)

with _mpl(Styler.background_gradient) as (plt, colors):
rng = s.max() - s.min()
smin = s.values.min()
smax = s.values.max()
rng = smax - smin
# extend lower / upper bounds, compresses color range
norm = colors.Normalize(s.min() - (rng * low),
s.max() + (rng * high))
# matplotlib modifies inplace?
norm = colors.Normalize(smin - (rng * low), smax + (rng * high))
# matplotlib colors.Normalize modifies inplace?
# https://github.com/matplotlib/matplotlib/issues/5427
normed = norm(s.values)
c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
if (not isinstance(text_color_threshold, (float, int)) or
not 0 <= text_color_threshold <= 1):
msg = "`text_color_threshold` must be a value from 0 to 1."
raise ValueError(msg)
rgbas = plt.cm.get_cmap(cmap)(norm(s.values))

def relative_luminance(color):
def relative_luminance(rgba):
"""
Calculate relative luminance of a color.

Expand All @@ -936,25 +937,33 @@ def relative_luminance(color):

Parameters
----------
color : matplotlib color
Hex code, rgb-tuple, or HTML color name.
color : rgb or rgba tuple

Returns
-------
float
The relative luminance as a value from 0 to 1
"""
rgb = colors.colorConverter.to_rgba_array(color)[:, :3]
rgb = np.where(rgb <= .03928, rgb / 12.92,
((rgb + .055) / 1.055) ** 2.4)
lum = rgb.dot([.2126, .7152, .0722])
return lum.item()

text_colors = ['#f1f1f1' if relative_luminance(x) <
text_color_threshold else '#000000' for x in c]

return ['background-color: {color};color: {tc}'.format(
color=color, tc=tc) for color, tc in zip(c, text_colors)]
r, g, b = (
x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055 ** 2.4)
for x in rgba[:3]
)
return 0.2126 * r + 0.7152 * g + 0.0722 * b

def css(rgba):
dark = relative_luminance(rgba) < text_color_threshold
text_color = '#f1f1f1' if dark else '#000000'
return 'background-color: {b};color: {c};'.format(
b=colors.rgb2hex(rgba), c=text_color
)

if s.ndim == 1:
return [css(rgba) for rgba in rgbas]
else:
return pd.DataFrame(
[[css(rgba) for rgba in row] for row in rgbas],
index=s.index, columns=s.columns
)

def set_properties(self, subset=None, **kwargs):
"""
Expand Down
28 changes: 28 additions & 0 deletions pandas/tests/io/formats/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -1056,6 +1056,34 @@ def test_text_color_threshold_raises(self, text_color_threshold):
df.style.background_gradient(
text_color_threshold=text_color_threshold)._compute()

@td.skip_if_no_mpl
def test_background_gradient_axis(self):
df = pd.DataFrame([[1, 2], [2, 4]], columns=['A', 'B'])

low = ['background-color: #f7fbff', 'color: #000000']
high = ['background-color: #08306b', 'color: #f1f1f1']
mid = ['background-color: #abd0e6', 'color: #000000']
result = df.style.background_gradient(cmap='Blues',
axis=0)._compute().ctx
assert result[(0, 0)] == low
assert result[(0, 1)] == low
assert result[(1, 0)] == high
assert result[(1, 1)] == high

result = df.style.background_gradient(cmap='Blues',
axis=1)._compute().ctx
assert result[(0, 0)] == low
assert result[(0, 1)] == high
assert result[(1, 0)] == low
assert result[(1, 1)] == high

result = df.style.background_gradient(cmap='Blues',
axis=None)._compute().ctx
assert result[(0, 0)] == low
assert result[(0, 1)] == mid
assert result[(1, 0)] == mid
assert result[(1, 1)] == high


def test_block_names():
# catch accidental removal of a block
Expand Down