@@ -1642,10 +1642,27 @@ def test_groupby_index(plot_cmp):
16421642 plot_cmp ("dotplot_groupby_index" )
16431643
16441644
1645- def test_groupby_list () -> None :
1646- """Test category order when groupby is a list.
1645+ def _mixed_with_nan (n : int ) -> np .ndarray :
1646+ col = np .array (["control" , 1 ] * (n // 2 ) + ["control" ] * (n % 2 ), dtype = object )
1647+ col [:10 ] = np .nan
1648+ return col
16471649
1648- See <https://github.com/scverse/scanpy/issues/1735>
1650+
1651+ @pytest .mark .parametrize (
1652+ "make_other" ,
1653+ [
1654+ pytest .param (lambda a : a .obs ["cell_type" ], id = "categorical" ),
1655+ pytest .param (
1656+ lambda a : pd .Categorical (np .arange (a .n_obs ) % 2 + 1 ), id = "int_categorical"
1657+ ),
1658+ pytest .param (lambda a : np .where (np .arange (a .n_obs ) % 2 , 2.0 , 0.5 ), id = "float" ),
1659+ pytest .param (lambda a : _mixed_with_nan (a .n_obs ), id = "mixed_with_nan" ),
1660+ ],
1661+ )
1662+ def test_groupby_list (make_other : Callable [[AnnData ], object ]) -> None :
1663+ """Test category order when groupby is a list, incl. non-string and missing values.
1664+
1665+ See <https://github.com/scverse/scanpy/issues/1735> and #4384.
16491666 """
16501667 rng = np .random .default_rng ()
16511668 adata = krumsiek11 ()
@@ -1654,25 +1671,28 @@ def test_groupby_list() -> None:
16541671 cats = adata .obs .cell_type .cat .categories .tolist ()
16551672 rng .shuffle (cats )
16561673 adata .obs ["rand_cat" ] = pd .Categorical (cat_val , categories = cats )
1674+ adata .obs ["other" ] = make_other (adata )
16571675
16581676 plot = sc .pl .dotplot (
16591677 adata ,
16601678 ["Gata1" , "Gata2" ],
1661- ["rand_cat" , "cell_type " ],
1679+ ["rand_cat" , "other " ],
16621680 swap_axes = True ,
16631681 show = False ,
16641682 return_fig = True ,
16651683 )
16661684 plot .make_figure ()
16671685 ticks = [t .get_text () for t in plot .get_axes ()["mainplot_ax" ].get_xticklabels ()]
16681686
1669- # each group’s categories determine the tick order, unobserved pairs are dropped
1670- observed = set (zip (adata .obs .rand_cat , adata .obs .cell_type , strict = True ))
1687+ # each group’s categories determine the tick order,
1688+ # unobserved pairs and rows with missing values are dropped
1689+ other = adata .obs ["other" ]
1690+ observed = set (zip (adata .obs .rand_cat , other , strict = True ))
16711691 assert ticks == [
1672- f"{ rand } _{ cell } "
1692+ f"{ rand } _{ o } "
16731693 for rand in cats
1674- for cell in adata . obs . cell_type .cat .categories
1675- if (rand , cell ) in observed
1694+ for o in other . astype ( "category" ) .cat .categories
1695+ if (rand , o ) in observed
16761696 ]
16771697
16781698
0 commit comments