Skip to content

Color text based on background color when using _background_gradient() #21263

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 2 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
47 changes: 38 additions & 9 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,7 @@ def highlight_null(self, null_color='red'):
return self

def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0,
subset=None):
subset=None, text_color=0.2):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To your question of what value to use as a default I don't have a preference visually, but if Seaborn is using 0.4 I'd rather just fall inline with that. Would certainly make the look and feel more consistent for users using both in say a Jupyter notebook

"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also add a Raises section for the docstring?

Color the background in a gradient according to
the data in each column (optionally row).
Expand All @@ -879,26 +879,30 @@ def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0,
1 or 'columns' for columnwise, 0 or 'index' for rowwise
subset: IndexSlice
a valid slice for ``data`` to limit the style application to
text_color: float or int
luminance threshold for determining text color. Facilitates text
visibility across varying background colors. From 0 to 1.
0 = all text is dark colored, 1 = all text is light colored.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can add a version added for 0.24.0 for this

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this the common name for this field in mpl?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMHO text_color=0.2 looks very counterintuitive to me. It almost looks like the exact opposite of what this feature is about (not having a constant text color).
Shouldn't the name at least contain "threshold", e.g. text_color_threshold?

Copy link
Contributor Author

@joelostblom joelostblom May 31, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that text_color_threshold is suitable, is it ok with multiple underscores in the parameter name? I don't think there is a common name for this in mpl (for coloring text in general, they tend to use just color, but I believe it would be easy to mistake that for the backgruond color here due to the method's name)


Returns
-------
self : Styler

Notes
-----
Tune ``low`` and ``high`` to keep the text legible by
not using the entire range of the color map. These extend
the range of the data by ``low * (x.max() - x.min())``
and ``high * (x.max() - x.min())`` before normalizing.
Set ``text_color`` or tune ``low`` and ``high`` to keep the text
legible by not using the entire range of the color map. The range of
the data is extended by ``low * (x.max() - x.min())`` and ``high *
(x.max() - x.min())`` before normalizing.
"""
subset = _maybe_numeric_slice(self.data, subset)
subset = _non_reducing_slice(subset)
self.apply(self._background_gradient, cmap=cmap, subset=subset,
axis=axis, low=low, high=high)
axis=axis, low=low, high=high, text_color=text_color)
return self

@staticmethod
def _background_gradient(s, cmap='PuBu', low=0, high=0):
def _background_gradient(s, cmap='PuBu', low=0, high=0, text_color=0.2):
"""Color background in a range according to the data."""
with _mpl(Styler.background_gradient) as (plt, colors):
rng = s.max() - s.min()
Expand All @@ -909,8 +913,33 @@ def _background_gradient(s, cmap='PuBu', low=0, high=0):
# https://github.com/matplotlib/matplotlib/issues/5427
normed = norm(s.values)
c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
return ['background-color: {color}'.format(color=color)
for color in c]
if (not isinstance(text_color, (float, int)) or
not 0 <= text_color <= 1):
msg = "`text_color` must be a value from 0 to 1."
raise ValueError(msg)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test to ensure this raises?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am having troubles getting the test correct for this. When I try the function manually, it raises ValueError when called with any one of the parameters in the test, but pytest keeps failing saying that it doesn't raise a ValueError. Would you have time to check my latest commits and advise?


def relative_luminance(color):
"""Calculate the relative luminance of a color according to W3C
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a standard for pandas docstrings you'll want to follow:

https://python-sprints.github.io/pandas/guide/pandas_docstring.html

Off the top of my head:

  • The first row should be only one line
  • The type and description of parameter(s) should be on separate lines
  • You'll want a space before the Returns section
  • Could add a Raises section for the bad luminance

standards, https://www.w3.org/WAI/GL/wiki/Relative_luminance
Parameters
----------
color : matplotlib color. Hex code, rgb-tuple, or
HTML color name.
Returns
-------
luminance : float between 0 and 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
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)]

def set_properties(self, subset=None, **kwargs):
"""
Expand Down
4 changes: 3 additions & 1 deletion pandas/tests/io/formats/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -1031,7 +1031,9 @@ def test_background_gradient(self):

result = df.style.background_gradient(
subset=pd.IndexSlice[1, 'A'])._compute().ctx
assert result[(1, 0)] == ['background-color: #fff7fb']

assert result[(1, 0)] == ['background-color: #fff7fb',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a more comprehensive / dedicated test for this? Something that encompasses the full range of expected values

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a suggestion

'color: #000000']


def test_block_names():
Expand Down