diff --git a/ultraplot/axes/plot.py b/ultraplot/axes/plot.py index e1e4ce9bf..fc17d3321 100644 --- a/ultraplot/axes/plot.py +++ b/ultraplot/axes/plot.py @@ -6913,7 +6913,7 @@ def raincloud( *, data: Any = None, positions: ArrayLike | None = None, - labels: Sequence[Any] | None = None, + labels: Sequence[Any] | str | None = None, orientation: Literal["vertical", "horizontal"] | None = None, vert: bool | None = None, autoformat: bool | None = None, @@ -6950,9 +6950,11 @@ def raincloud( as an alternative to passing the observations positionally. positions : sequence of float, optional Distinct group centres. Defaults to ``range(number_of_groups)``. - labels : sequence of str, optional - Group tick and legend labels. With automatic formatting, infer - column labels from pandas or xarray input. + labels : str or sequence of str, optional + A string repeats as literal tick and legend text for each group. + A sequence supplies one label per distribution, in input order. + To use a column's values, pass it explicitly as ``labels=df["name"]``. + When omitted, automatic formatting infers labels from pandas or xarray. orientation : {'vertical', 'horizontal'}, default: :rc:`raincloud.orientation` Direction of the measured variable. For horizontal plots, group centres lie on the y axis. diff --git a/ultraplot/axes/plot_types/raincloud.py b/ultraplot/axes/plot_types/raincloud.py index fa55ace06..5bb0fb038 100644 --- a/ultraplot/axes/plot_types/raincloud.py +++ b/ultraplot/axes/plot_types/raincloud.py @@ -172,7 +172,7 @@ def _resolve_options( def _infer_metadata( - data: Any, labels: Sequence[Any] | None, autoformat: bool | None + data: Any, labels: Sequence[Any] | str | None, autoformat: bool | None ) -> tuple[Any, Sequence[Any] | None, str | None, str | None]: """Extract labelled-array metadata without overriding explicit labels.""" autoformat = _not_none(autoformat, rc["autoformat"]) @@ -210,7 +210,7 @@ def _split_distributions(data: Any) -> Iterable[ArrayLike]: def _prepare_data( data: Any, positions: ArrayLike | None, - labels: Sequence[Any] | None, + labels: Sequence[Any] | str | None, autoformat: bool | None, ) -> _RaincloudData: """Clean observations and validate group labels and positions.""" @@ -226,8 +226,13 @@ def _prepare_data( n = len(cleaned) if not n or not any(values.size for values in cleaned): raise ValueError("No finite observations to plot") - if labels is not None and (isinstance(labels, str) or len(labels) != n): - raise ValueError("Number of labels must match number of distributions") + if isinstance(labels, str): + labels = [labels] * n + elif labels is not None: + if len(labels) != n: + raise ValueError("Number of labels must match number of distributions") + # Consume Series values in order, including those with non-default indices. + labels = list(labels) positions = ( np.arange(n, dtype=float) if positions is None @@ -477,7 +482,7 @@ def raincloud( data: Any, *, positions: ArrayLike | None = None, - labels: Sequence[Any] | None = None, + labels: Sequence[Any] | str | None = None, orientation: Literal["vertical", "horizontal"] | None = None, autoformat: bool | None = None, legend: bool | str | int | None = None, diff --git a/ultraplot/tests/test_raincloud.py b/ultraplot/tests/test_raincloud.py index a6c5dc083..0d47f86fe 100644 --- a/ultraplot/tests/test_raincloud.py +++ b/ultraplot/tests/test_raincloud.py @@ -562,3 +562,25 @@ def test_raincloud_rc_file_and_context_restore(tmp_path: Path) -> None: -0.15 ) assert uplt.rc["raincloud.side"] == original + + +@pytest.mark.parametrize("use_column", [False, True]) +def test_raincloud_explicit_labels_with_data_lookup(use_column): + from matplotlib.legend import Legend + + pd = pytest.importorskip("pandas") + frame = pd.DataFrame({"first": [1, 2, 3], "second": [3, 4, 5]}) + names = pd.DataFrame({"name": ["Treatment", "Control"]}, index=[20, 10]) + labels = names["name"] if use_column else "name" + expected = ["Treatment", "Control"] if use_column else ["name", "name"] + fig, ax = uplt.subplot() + ax.raincloud( + "samples", + data={"samples": frame, "name": names["name"]}, + labels=labels, + legend=True, + ) + fig.canvas.draw() + assert [t.get_text() for t in ax.get_xticklabels()] == expected + (legend,) = fig.findobj(Legend) + assert [t.get_text() for t in legend.get_texts()] == expected