Skip to content

Add consistent legend support across backends #115

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

Merged
merged 3 commits into from
May 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/arviz_plots/backend/bokeh/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ def legend(
artist_type="line",
artist_kwargs=None,
legend_target=None,
side="right",
side="auto",
legend_placement_threshold=600, # Magic number
**kwargs,
):
"""Generate a legend on a figure given lists of labels and property kwargs.
Expand Down Expand Up @@ -61,6 +62,14 @@ def legend(
for kws in kwarg_list:
glyph = artist_fun(**{**artist_kwargs, **kws})
glyph_list.append(glyph)

if side == "auto":
plot_width = target_plot.width
if plot_width >= legend_placement_threshold:
side = "right"
else:
side = "center"

leg = Legend(
items=[(str(label), [glyph]) for label, glyph in zip(label_list, glyph_list)],
title=title,
Expand Down
15 changes: 2 additions & 13 deletions src/arviz_plots/backend/none/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

import numpy as np

from .legend import legend

ALLOW_KWARGS = True


Expand Down Expand Up @@ -532,16 +534,3 @@ def grid(target, axis, color):
}
target.append(artist_element)
return artist_element


def legend(
target,
kwarg_list,
label_list,
title=None, # pylint: disable=redefined-outer-name
artist_type="line",
artist_kwargs=None,
**kwargs,
):
"""Interface to manually generated legends."""
raise NotImplementedError("No legends in 'none' backend.")
25 changes: 25 additions & 0 deletions src/arviz_plots/backend/none/legend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""None backend manual legend generation.

For now only used for documentation purposes.
"""


# pylint: disable=unused-argument
def legend(
target, kwarg_list, label_list, title=None, artist_type="line", artist_kwargs=None, **kwargs
):
"""Generate a legend on a figure given lists of labels and property kwargs.

Parameters
----------
target : plot object
kwarg_list : sequence of mapping
label_list : sequence of str
title : str, optional
artist_type : {"line", "scatter", "rectangle"}, default "line"
artist_kwargs : mapping, optional
Passed to all artists when generating legend miniatures.
**kwargs
Passed to backend legend generating function.
"""
return None
1 change: 1 addition & 0 deletions src/arviz_plots/backend/plotly/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from webcolors import hex_to_rgb, name_to_rgb

from ..none import get_default_aes as get_agnostic_default_aes
from .legend import legend


class UnsetDefault:
Expand Down
54 changes: 52 additions & 2 deletions src/arviz_plots/backend/plotly/legend.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,58 @@
"""Plotly legend generation."""


def dealiase_line_kwargs(kwargs):
"""Convert arviz common interface properties to plotly ones."""
prop_map = {"linewidth": "width", "linestyle": "dash"}
return {prop_map.get(key, key): value for key, value in kwargs.items()}


def legend(
target, kwarg_list, label_list, title=None, artist_type="line", artist_kwargs=None, **kwargs
):
"""Generate a legend with plotly."""
raise NotImplementedError("Still in progress")
"""Generate a legend with plotly.

Parameters
----------
target : plotly.graph_objects.Figure
The figure to add the legend to
kwarg_list : list
List of style dictionaries for each legend entry
label_list : list
List of labels for each legend entry
title : str, optional
Title of the legend
artist_type : str, optional
Type of artist to use for legend entries. Currently only "line" is supported.
artist_kwargs : dict, optional
Additional kwargs passed to all artists
**kwargs : dict
Additional kwargs passed to legend configuration

Returns
-------
None
The legend is added to the target figure inplace
"""
if artist_kwargs is None:
artist_kwargs = {}

if artist_type == "line":
artist_fun = target.add_scatter
kwarg_list = [dealiase_line_kwargs(kws) for kws in kwarg_list]
mode = "lines"
else:
raise NotImplementedError("Only line type legends supported for now")

for kws, label in zip(kwarg_list, label_list):
artist_fun(
x=[None],
y=[None],
name=str(label),
mode=mode,
line=kws,
showlegend=True,
**artist_kwargs,
)

target.update_layout(showlegend=True, legend_title_text=title, **kwargs)
6 changes: 6 additions & 0 deletions src/arviz_plots/plots/psense_dist_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,4 +274,10 @@ def plot_psense_dist(
stats_kwargs=stats_kwargs,
)

# Add legend for alpha parameter automatically
plot_collection.add_legend(
"alpha",
title="Power Scale Factor",
)

return plot_collection