Skip to content

Commit fd3b741

Browse files
Merge pull request #2544 from plotly/fix-hover-labels
fixed bug in hover data
2 parents d191458 + 23ef3b8 commit fd3b741

File tree

3 files changed

+31
-4
lines changed

3 files changed

+31
-4
lines changed

Diff for: CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
77
### Fixed
88

99
- Fixed special cases with `px.sunburst` and `px.treemap` with `path` input ([#2524](https://github.com/plotly/plotly.py/pull/2524))
10+
- 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)).
1011

1112
## [4.8.1] - 2020-05-28
1213

Diff for: packages/python/plotly/plotly/express/_core.py

+18-4
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,18 @@ def get_label(args, column):
116116
return column
117117

118118

119+
def invert_label(args, column):
120+
"""Invert mapping.
121+
Find key corresponding to value column in dict args["labels"].
122+
Returns `column` if the value does not exist.
123+
"""
124+
reversed_labels = {value: key for (key, value) in args["labels"].items()}
125+
try:
126+
return reversed_labels[column]
127+
except Exception:
128+
return column
129+
130+
119131
def _is_continuous(df, col_name):
120132
return df[col_name].dtype.kind in "ifc"
121133

@@ -434,11 +446,13 @@ def make_trace_kwargs(args, trace_spec, trace_data, mapping_labels, sizeref):
434446
mapping_labels_copy = OrderedDict(mapping_labels)
435447
if args["hover_data"] and isinstance(args["hover_data"], dict):
436448
for k, v in mapping_labels.items():
437-
if k in args["hover_data"]:
438-
if args["hover_data"][k][0]:
439-
if isinstance(args["hover_data"][k][0], str):
449+
# We need to invert the mapping here
450+
k_args = invert_label(args, k)
451+
if k_args in args["hover_data"]:
452+
if args["hover_data"][k_args][0]:
453+
if isinstance(args["hover_data"][k_args][0], str):
440454
mapping_labels_copy[k] = v.replace(
441-
"}", "%s}" % args["hover_data"][k][0]
455+
"}", "%s}" % args["hover_data"][k_args][0]
442456
)
443457
else:
444458
_ = mapping_labels_copy.pop(k)

Diff for: packages/python/plotly/plotly/tests/test_core/test_px/test_px_hover.py

+12
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,18 @@ def test_newdatain_hover_data():
7272
)
7373

7474

75+
def test_formatted_hover_and_labels():
76+
df = px.data.tips()
77+
fig = px.scatter(
78+
df,
79+
x="tip",
80+
y="total_bill",
81+
hover_data={"total_bill": ":.1f"},
82+
labels={"total_bill": "Total bill"},
83+
)
84+
assert ":.1f" in fig.data[0].hovertemplate
85+
86+
7587
def test_fail_wrong_column():
7688
with pytest.raises(ValueError) as err_msg:
7789
px.scatter(

0 commit comments

Comments
 (0)