-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
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 23 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 |
---|---|---|
|
@@ -1241,4 +1241,4 @@ | |
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 1 | ||
} | ||
} | ||
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -159,7 +159,7 @@ def __init__( | |
self.index = data.index | ||
self.columns = data.columns | ||
|
||
self.uuid = uuid | ||
self.uuid = uuid or str(uuid1()).replace("-", "_") | ||
self.table_styles = table_styles | ||
self.caption = caption | ||
if precision is None: | ||
|
@@ -171,6 +171,8 @@ def __init__( | |
self.cell_ids = cell_ids | ||
self.na_rep = na_rep | ||
|
||
self.tooltips = _Tooltips() | ||
attack68 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
# display_funcs maps (row, col) -> formatting function | ||
|
||
def default_display_func(x): | ||
|
@@ -192,6 +194,91 @@ 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 = Styler(df, uuid="_").set_tooltips(ttips).render() | ||
attack68 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
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[List[Tuple[str, Union[str, int, float]]]] = None, | ||
attack68 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) -> "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 property ('visibility', 'hidden') should always be included in any manual | ||
properties specification, to allow for HTML on hover functionality. | ||
|
||
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, | ||
|
@@ -246,7 +333,7 @@ def _translate(self): | |
precision = self.precision | ||
hidden_index = self.hidden_index | ||
hidden_columns = self.hidden_columns | ||
uuid = self.uuid or str(uuid1()).replace("-", "_") | ||
uuid = self.uuid | ||
ROW_HEADING_CLASS = "row_heading" | ||
COL_HEADING_CLASS = "col_heading" | ||
INDEX_NAME_CLASS = "index_name" | ||
|
@@ -540,6 +627,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) | ||
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. this is best before the update(), because it is a direct extension of the previous _translate() method. 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. this is very confusing here, why is this not part of _translate itself? |
||
# 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 | ||
|
@@ -609,6 +697,7 @@ def clear(self) -> None: | |
Returns None. | ||
""" | ||
self.ctx.clear() | ||
self.tooltips = _Tooltips() | ||
attack68 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self._todo = [] | ||
|
||
def _compute(self): | ||
|
@@ -1516,6 +1605,148 @@ 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: List[Tuple[str, Union[str, int, float]]] = [ | ||
attack68 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
("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): | ||
return [{"selector": f".{self.class_name}", "props": self.class_properties}] | ||
|
||
def _translate_tooltips(self, styler_data, uuid, d): | ||
attack68 marked this conversation as resolved.
Show resolved
Hide resolved
attack68 marked this conversation as resolved.
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. | ||
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 | ||
|
||
def pseudo_css(uuid, row, col, name, text): | ||
attack68 marked this conversation as resolved.
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")]}] | ||
|
||
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
|
||
d | ||
for sublist in [ | ||
pseudo_css(uuid, i, j, self.class_name, str(self.tt_data.iloc[i, j]),) | ||
for i, rn in enumerate(self.tt_data.index) | ||
attack68 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for j, cn in enumerate(self.tt_data.columns) | ||
if not mask.iloc[i, j] | ||
] | ||
for d 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}). | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you revert this
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i've no real experience with selected git revert, doesn't it just get squashed?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
git checkout upstream/master doc/source/user_guide/style.ipynb
and commit the result