-
-
Notifications
You must be signed in to change notification settings - Fork 19.1k
ENH: Styler tooltips feature #35643
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
ENH: Styler tooltips feature #35643
Changes from 42 commits
3e83fc6
f8ffbbe
b92d255
cd6c5f2
1f61e87
af83833
078c0bb
eeddd19
6389811
e7557f5
64f789a
0b1e930
5ca86a5
f798852
1e782b7
ee952de
71c3cc1
2c36d4b
4aed112
49ecb50
3510ada
7f76e8e
aa09003
f160297
776c434
c3c0aba
dd69ae6
4055e1b
6b27ec2
8fc8437
a96acf8
50c2aa9
607cfe6
ab079b0
f6e066e
af6401a
0e6b1a3
5829546
eaa851e
9e8612f
5507c4f
d0eefca
c0b004e
e4a5e20
849b1f4
950b3b1
efc7fca
eb7fe68
5a377b8
54c52da
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -181,6 +181,8 @@ def __init__( | |
self.cell_ids = cell_ids | ||
self.na_rep = na_rep | ||
|
||
self.tooltips = _Tooltips() | ||
|
||
self.cell_context: Dict[str, Any] = {} | ||
|
||
# display_funcs maps (row, col) -> formatting function | ||
|
@@ -204,6 +206,101 @@ def _repr_html_(self) -> str: | |
""" | ||
return self.render() | ||
|
||
def set_tooltips(self, ttips: DataFrame) -> "Styler": | ||
attack68 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Add string based tooltips that will appear in the `Styler` HTML result. These | ||
jreback marked this conversation as resolved.
Show resolved
Hide resolved
|
||
tooltips are applicable only to`<td>` elements. | ||
|
||
Parameters | ||
---------- | ||
ttips : DataFrame | ||
DataFrame containing strings that will be translated to tooltips, mapped | ||
by identical column and index values that must exist on the underlying | ||
`Styler` data. None, NaN values, and empty strings will be ignored and | ||
not affect the rendered HTML. | ||
|
||
Returns | ||
------- | ||
self : Styler | ||
|
||
Notes | ||
----- | ||
Tooltips are created by adding `<span class="pd-t"></span>` to each data cell | ||
and then manipulating the table level CSS to attach pseudo hover and pseudo | ||
after selectors to produce the required the results. For styling control | ||
see `:meth:Styler.set_tooltips_class`. | ||
Tooltips are not designed to be efficient, and can add large amounts of | ||
additional HTML for larger tables, since they also require that `cell_ids` | ||
is forced to `True`. | ||
|
||
Examples | ||
-------- | ||
>>> df = pd.DataFrame(data=[[0, 1], [2, 3]]) | ||
>>> ttips = pd.DataFrame( | ||
... data=[["Min", ""], [np.nan, "Max"]], columns=df.columns, index=df.index | ||
... ) | ||
>>> s = df.style.set_tooltips(ttips).render() | ||
""" | ||
if not self.cell_ids: | ||
# tooltips not optimised for individual cell check. | ||
raise NotImplementedError( | ||
"Tooltips can only render with 'cell_ids' is True." | ||
) | ||
self.tooltips.tt_data = ttips | ||
return self | ||
|
||
def set_tooltips_class( | ||
self, | ||
name: Optional[str] = None, | ||
properties: Optional[Sequence[Tuple[str, Union[str, int, float]]]] = None, | ||
) -> "Styler": | ||
""" | ||
Manually configure the name and/or properties of the class for | ||
creating tooltips on hover. | ||
|
||
Parameters | ||
---------- | ||
name : str, default None | ||
Name of the tooltip class used in CSS, should conform to HTML standards. | ||
properties : list-like, default None | ||
List of (attr, value) tuples; see example. | ||
|
||
Returns | ||
------- | ||
self : Styler | ||
|
||
Notes | ||
----- | ||
If arguments are `None` will not make any changes to the underlying ``Tooltips`` | ||
existing values. | ||
|
||
The default properties for the tooltip CSS class are: | ||
|
||
- visibility: hidden | ||
- position: absolute | ||
- z-index: 1 | ||
- background-color: black | ||
- color: white | ||
- transform: translate(-20px, -20px) | ||
|
||
The property ('visibility', 'hidden') is a key prerequisite to the hover | ||
functionality, and should always be included in any manual properties | ||
specification. | ||
|
||
Examples | ||
-------- | ||
>>> df = pd.DataFrame(np.random.randn(10, 4)) | ||
>>> df.style.set_tooltips_class(name='tt-add', properties=[ | ||
... ('visibility', 'hidden'), | ||
... ('position', 'absolute'), | ||
... ('z-index', 1)]) | ||
""" | ||
if properties: | ||
self.tooltips.class_properties = properties | ||
if name: | ||
self.tooltips.class_name = name | ||
return self | ||
|
||
@doc(NDFrame.to_excel, klass="Styler") | ||
def to_excel( | ||
self, | ||
|
@@ -616,6 +713,7 @@ def render(self, **kwargs) -> str: | |
self._compute() | ||
# TODO: namespace all the pandas keys | ||
d = self._translate() | ||
d = self.tooltips._translate_tooltips(self.data, self.uuid, d) | ||
|
||
# filter out empty styles, every cell will have a class | ||
# but the list of props may just be [['', '']]. | ||
# so we have the nested anys below | ||
|
@@ -685,6 +783,7 @@ def clear(self) -> None: | |
Returns None. | ||
""" | ||
self.ctx.clear() | ||
self.tooltips = _Tooltips() | ||
attack68 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
self.cell_context = {} | ||
self._todo = [] | ||
|
||
|
@@ -1589,6 +1688,170 @@ def pipe(self, func: Callable, *args, **kwargs): | |
return com.pipe(self, func, *args, **kwargs) | ||
|
||
|
||
class _Tooltips: | ||
""" | ||
An extension to ``Styler`` that allows for and manipulates tooltips on hover | ||
of table data-cells in the HTML result. | ||
|
||
Parameters | ||
---------- | ||
css_name: str, default "pd-t" | ||
Name of the CSS class that controls visualisation of tooltips. | ||
css_props: list-like, default; see Notes | ||
List of (attr, value) tuples defining properties of the CSS class. | ||
tooltips: DataFrame, default empty | ||
DataFrame of strings aligned with underlying ``Styler`` data for tooltip | ||
display. | ||
|
||
Notes | ||
----- | ||
The default properties for the tooltip CSS class are: | ||
|
||
- visibility: hidden | ||
- position: absolute | ||
- z-index: 1 | ||
- background-color: black | ||
- color: white | ||
- transform: translate(-20px, -20px) | ||
|
||
Hidden visibility is a key prerequisite to the hover functionality, and should | ||
always be included in any manual properties specification. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
css_props: Sequence[Tuple[str, Union[str, int, float]]] = [ | ||
("visibility", "hidden"), | ||
("position", "absolute"), | ||
("z-index", 1), | ||
("background-color", "black"), | ||
("color", "white"), | ||
("transform", "translate(-20px, -20px)"), | ||
jreback marked this conversation as resolved.
Show resolved
Hide resolved
|
||
], | ||
css_name: str = "pd-t", | ||
tooltips: DataFrame = DataFrame(), | ||
): | ||
self.class_name = css_name | ||
self.class_properties = css_props | ||
self.tt_data = tooltips | ||
self.table_styles: List[Dict[str, Union[str, List[Tuple[str, str]]]]] = [] | ||
jreback marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
@property | ||
def _class_styles(self): | ||
""" | ||
Combine the ``_Tooltips`` CSS class name and CSS properties to the format | ||
required to extend the underlying ``Styler`` `table_styles` to allow | ||
tooltips to render in HTML. | ||
|
||
Returns | ||
------- | ||
styles : List | ||
""" | ||
return [{"selector": f".{self.class_name}", "props": self.class_properties}] | ||
|
||
def _translate_tooltips(self, styler_data, uuid, d): | ||
attack68 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
attack68 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
""" | ||
Mutate the render dictionary to allow for tooltips: | ||
|
||
- Add `<span>` HTML element to each data cells `display_value`. Ignores | ||
headers. | ||
- Add table level CSS styles to control pseudo classes. | ||
|
||
Parameters | ||
---------- | ||
styler_data : DataFrame | ||
Underlying ``Styler`` DataFrame used for reindexing. | ||
uuid : str | ||
The underlying ``Styler`` uuid for CSS id. | ||
d : dict | ||
The dictionary prior to final render | ||
""" | ||
self.tt_data = ( | ||
self.tt_data.reindex_like(styler_data) | ||
.dropna(how="all", axis=0) | ||
.dropna(how="all", axis=1) | ||
) | ||
if self.tt_data.empty: | ||
return d | ||
|
||
name = self.class_name | ||
|
||
def _pseudo_css(row: int, col: int, text: str): | ||
attack68 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
""" | ||
For every table data-cell that has a valid tooltip (not None, NaN or | ||
empty string) must create two pseudo CSS entries for the specific | ||
<td> element id which are added to overall table styles: | ||
an on hover visibility change and a content change | ||
dependent upon the user's chosen display string. | ||
|
||
For example: | ||
[{"selector": "T__row1_col1:hover .pd-t", | ||
"props": [("visibility", "visible")]}, | ||
{"selector": "T__row1_col1 .pd-t::after", | ||
"props": [("content", "Some Valid Text String")]}] | ||
|
||
Parameters | ||
---------- | ||
row : int | ||
The row index of the specified tooltip string data | ||
col : int | ||
The col index of the specified tooltip string data | ||
text : str | ||
The textual content of the tooltip to be displayed in HTML. | ||
|
||
Returns | ||
------- | ||
pseudo_css : List | ||
""" | ||
return [ | ||
{ | ||
"selector": "#T_" | ||
+ uuid | ||
+ "row" | ||
+ str(row) | ||
+ "_col" | ||
+ str(col) | ||
+ f":hover .{name}", | ||
"props": [("visibility", "visible")], | ||
}, | ||
{ | ||
"selector": "#T_" | ||
+ uuid | ||
+ "row" | ||
+ str(row) | ||
+ "_col" | ||
+ str(col) | ||
+ f" .{name}::after", | ||
"props": [("content", f'"{text}"')], | ||
}, | ||
] | ||
|
||
mask = (self.tt_data.isna()) | (self.tt_data.eq("")) # empty string = no ttip | ||
jreback marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.table_styles = [ | ||
jreback marked this conversation as resolved.
Show resolved
Hide resolved
|
||
style | ||
for sublist in [ | ||
_pseudo_css(i, j, str(self.tt_data.iloc[i, j])) | ||
for i in range(len(self.tt_data.index)) | ||
for j in range(len(self.tt_data.columns)) | ||
if not mask.iloc[i, j] | ||
] | ||
for style in sublist | ||
] | ||
|
||
if self.table_styles: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i am puzzled by this here why this is involved at all There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the above There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ok can you add that as a comment There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can you update this There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i added a comment line 1938? |
||
for row in d["body"]: | ||
for item in row: | ||
if item["type"] == "td": | ||
item["display_value"] = ( | ||
str(item["display_value"]) | ||
+ f'<span class="{self.class_name}"></span>' | ||
) | ||
d["table_styles"].extend(self._class_styles) | ||
d["table_styles"].extend(self.table_styles) | ||
|
||
return d | ||
|
||
|
||
def _is_visible(idx_row, idx_col, lengths) -> bool: | ||
""" | ||
Index -> {(idx_row, idx_col): bool}). | ||
|
Uh oh!
There was an error while loading. Please reload this page.