diff --git a/CHANGELOG.md b/CHANGELOG.md index 985f3c231d0..5aca477f453 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/packages/python/plotly/plotly/express/_core.py b/packages/python/plotly/plotly/express/_core.py index df600555b14..5d6388ae59d 100644 --- a/packages/python/plotly/plotly/express/_core.py +++ b/packages/python/plotly/plotly/express/_core.py @@ -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" @@ -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) diff --git a/packages/python/plotly/plotly/tests/test_core/test_px/test_px_hover.py b/packages/python/plotly/plotly/tests/test_core/test_px/test_px_hover.py index f63696e8dee..07d0e201a43 100644 --- a/packages/python/plotly/plotly/tests/test_core/test_px/test_px_hover.py +++ b/packages/python/plotly/plotly/tests/test_core/test_px/test_px_hover.py @@ -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(