Skip to content

Commit

Permalink
Merge pull request #2544 from plotly/fix-hover-labels
Browse files Browse the repository at this point in the history
fixed bug in hover data
  • Loading branch information
nicolaskruchten authored Jun 22, 2020
2 parents d191458 + 23ef3b8 commit fd3b741
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
### Fixed

- Fixed special cases with `px.sunburst` and `px.treemap` with `path` input ([#2524](https://github.com/plotly/plotly.py/pull/2524))
- Fixed bug in `hover_data` argument of `px` functions, when the column name is changed with labels and `hover_data` is a dictionary setting up a specific format for the hover data ([#2544](https://github.com/plotly/plotly.py/pull/2544)).

## [4.8.1] - 2020-05-28

Expand Down
22 changes: 18 additions & 4 deletions packages/python/plotly/plotly/express/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,18 @@ def get_label(args, column):
return column


def invert_label(args, column):
"""Invert mapping.
Find key corresponding to value column in dict args["labels"].
Returns `column` if the value does not exist.
"""
reversed_labels = {value: key for (key, value) in args["labels"].items()}
try:
return reversed_labels[column]
except Exception:
return column


def _is_continuous(df, col_name):
return df[col_name].dtype.kind in "ifc"

Expand Down Expand Up @@ -434,11 +446,13 @@ def make_trace_kwargs(args, trace_spec, trace_data, mapping_labels, sizeref):
mapping_labels_copy = OrderedDict(mapping_labels)
if args["hover_data"] and isinstance(args["hover_data"], dict):
for k, v in mapping_labels.items():
if k in args["hover_data"]:
if args["hover_data"][k][0]:
if isinstance(args["hover_data"][k][0], str):
# We need to invert the mapping here
k_args = invert_label(args, k)
if k_args in args["hover_data"]:
if args["hover_data"][k_args][0]:
if isinstance(args["hover_data"][k_args][0], str):
mapping_labels_copy[k] = v.replace(
"}", "%s}" % args["hover_data"][k][0]
"}", "%s}" % args["hover_data"][k_args][0]
)
else:
_ = mapping_labels_copy.pop(k)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,18 @@ def test_newdatain_hover_data():
)


def test_formatted_hover_and_labels():
df = px.data.tips()
fig = px.scatter(
df,
x="tip",
y="total_bill",
hover_data={"total_bill": ":.1f"},
labels={"total_bill": "Total bill"},
)
assert ":.1f" in fig.data[0].hovertemplate


def test_fail_wrong_column():
with pytest.raises(ValueError) as err_msg:
px.scatter(
Expand Down

0 comments on commit fd3b741

Please sign in to comment.