Skip to content
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
10 changes: 6 additions & 4 deletions ultraplot/axes/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
15 changes: 10 additions & 5 deletions ultraplot/axes/plot_types/raincloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down Expand Up @@ -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."""
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down
22 changes: 22 additions & 0 deletions ultraplot/tests/test_raincloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -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