Skip to content

Commit ce4de5e

Browse files
committed
multi-panel
1 parent 354d05e commit ce4de5e

2 files changed

Lines changed: 71 additions & 42 deletions

File tree

‎src/scanpy/plotting/legacy/_anndata.py‎

Lines changed: 44 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -874,18 +874,34 @@ def violin( # noqa: PLR0912, PLR0913, PLR0915
874874
raise ValueError(msg)
875875

876876
user_hue = kwds.get("hue")
877-
if groupby is not None:
878-
obs_df = get.obs_df(
879-
adata,
880-
keys=list(
881-
dict.fromkeys([groupby, *keys, *([user_hue] if user_hue else [])])
882-
),
883-
layer=layer,
884-
use_raw=use_raw,
877+
obs_df = get.obs_df(
878+
adata,
879+
keys=list(
880+
dict.fromkeys(k for k in [groupby, *keys, user_hue] if k is not None)
881+
),
882+
layer=layer,
883+
use_raw=use_raw,
884+
)
885+
if groupby is None:
886+
obs_tidy = pd.melt(
887+
obs_df, value_vars=keys, id_vars=[user_hue] if user_hue else None
885888
)
886-
hue_key = user_hue or groupby
887-
kwds["hue"] = hue_key
889+
x = "variable"
890+
ys = ["value"]
891+
else:
892+
obs_tidy = obs_df
893+
x = groupby
894+
ys = keys
895+
hue_key = kwds["hue"] = user_hue or groupby
888896
if kwds.get("palette") is None:
897+
if not isinstance(adata.obs[groupby].dtype, CategoricalDtype):
898+
msg = (
899+
f"The column `adata.obs[{groupby!r}]` needs to be categorical, "
900+
f"but is of dtype {adata.obs[groupby].dtype}."
901+
)
902+
raise ValueError(msg)
903+
# A user-supplied non-categorical hue is left to seaborn's own
904+
# palette handling (e.g. a continuous colormap).
889905
if isinstance(adata.obs[hue_key].dtype, CategoricalDtype):
890906
_utils.add_colors_for_categorical_sample_annotation(adata, hue_key)
891907
kwds["palette"] = dict(
@@ -895,31 +911,25 @@ def violin( # noqa: PLR0912, PLR0913, PLR0915
895911
strict=True,
896912
)
897913
)
898-
elif user_hue is None:
899-
msg = (
900-
f"The column `adata.obs[{groupby!r}]` needs to be categorical, "
901-
f"but is of dtype {adata.obs[groupby].dtype}."
902-
)
903-
raise ValueError(msg)
904-
# A user-supplied non-categorical hue is left to seaborn's own
905-
# palette handling (e.g. a continuous colormap).
906-
else:
907-
obs_df = get.obs_df(
908-
adata,
909-
keys=list(dict.fromkeys([*keys, *([user_hue] if user_hue else [])])),
910-
layer=layer,
911-
use_raw=use_raw,
914+
915+
# When the user colors violins by a second grouping, dodge the
916+
# strip points the same way so they land on their violins.
917+
if user_hue is not None and user_hue != groupby:
918+
hue_col = obs_tidy[user_hue]
919+
levels = (
920+
hue_col.cat.categories
921+
if isinstance(hue_col.dtype, CategoricalDtype)
922+
else hue_col.unique()
912923
)
913-
if groupby is None:
914-
obs_tidy = pd.melt(
915-
obs_df, value_vars=keys, id_vars=[user_hue] if user_hue else None
924+
# `color` + `hue` would make a gradient, so map every level to black
925+
strip_kw = dict(
926+
hue=user_hue,
927+
dodge=True,
928+
legend=False,
929+
palette=dict.fromkeys(levels, "black"),
916930
)
917-
x = "variable"
918-
ys = ["value"]
919931
else:
920-
obs_tidy = obs_df
921-
x = groupby
922-
ys = keys
932+
strip_kw = dict(color="black")
923933

924934
if multi_panel and groupby is None and len(ys) == 1:
925935
# This is a quick and dirty way for adapting scales across several
@@ -948,8 +958,8 @@ def violin( # noqa: PLR0912, PLR0913, PLR0915
948958
data=grouped_df.get_group(key),
949959
jitter=jitter,
950960
size=size,
951-
color="black",
952961
ax=g.axes_dict[key],
962+
**strip_kw,
953963
)
954964
if log:
955965
g.set(yscale="log")
@@ -999,23 +1009,15 @@ def violin( # noqa: PLR0912, PLR0913, PLR0915
9991009
**kwds,
10001010
)
10011011
if stripplot:
1002-
# When the user colors violins by a second grouping, dodge the
1003-
# strip points the same way so they land on their violins.
1004-
strip_hue = (
1005-
{"hue": kwds["hue"], "dodge": True, "legend": False}
1006-
if kwds.get("hue") and kwds["hue"] != x
1007-
else {}
1008-
)
10091012
sns.stripplot(
10101013
x=x,
10111014
y=y,
10121015
data=obs_tidy,
10131016
order=order,
10141017
jitter=jitter,
1015-
color="black",
10161018
size=size,
10171019
ax=ax_base,
1018-
**strip_hue,
1020+
**strip_kw,
10191021
)
10201022
if xlabel == "" and groupby is not None and rotation is None:
10211023
xlabel = groupby.replace("_", " ")

‎tests/plotting/legacy/test_plotting.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,33 @@ def test_violin(subtests: pytest.Subtests, exit_stack: ExitStack, plot_cmp) -> N
674674
plt.close(fig)
675675

676676

677+
@pytest.mark.parametrize(
678+
"kw",
679+
[
680+
pytest.param(dict(groupby="bulk_labels"), id="groupby"),
681+
pytest.param(dict(multi_panel=True), id="multi_panel"),
682+
],
683+
)
684+
def test_violin_hue_stripplot(kw: dict[str, object]) -> None:
685+
sc.pl.violin(pbmc68k_reduced(), "n_genes", hue="phase", show=False, **kw)
686+
for ax in plt.gcf().axes:
687+
strips = [
688+
c
689+
for c in ax.collections
690+
if isinstance(c, mpl.collections.PathCollection) and len(c.get_offsets())
691+
]
692+
# points are split like the violins (one strip per hue level) …
693+
assert len(strips) > 1
694+
centers = {
695+
round(float(np.asarray(c.get_offsets())[:, 0].mean()), 1) for c in strips
696+
}
697+
assert len(centers) == len(strips)
698+
# … and stay black
699+
for c in strips:
700+
np.testing.assert_array_equal(c.get_facecolor()[:, :3], 0)
701+
plt.close("all")
702+
703+
677704
# TODO: Generalize test to more plotting types
678705
def test_violin_without_raw(tmp_path):
679706
# https://github.com/scverse/scanpy/issues/1546

0 commit comments

Comments
 (0)