scuva 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
scuva/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """Public package exports for scuva."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .text import wrap_join, rename, clean_title
6
+ from .graphing import set_categorical_colors, get_categorical_colormap, subplots_with_side_axis
7
+ from .graphing.legend import make_colorbar, make_legend
8
+ from .graphing.umap import multiple_umap, umap, umap_split
9
+ from .graphing.composition import graph_counts, graph_proportions
10
+
11
+ __all__ = [
12
+ "__version__",
13
+ "umap",
14
+ "multiple_umap",
15
+ "umap_split",
16
+ "graph_counts",
17
+ "graph_proportions",
18
+ "make_colorbar",
19
+ "make_legend",
20
+ "wrap_join",
21
+ "rename",
22
+ "clean_title",
23
+ "set_categorical_colors",
24
+ "get_categorical_colormap",
25
+ "subplots_with_side_axis",
26
+ ]
@@ -0,0 +1,138 @@
1
+ """Shared plotting utilities for categorical colors and figure layout."""
2
+
3
+ from typing import Literal
4
+
5
+ from matplotlib import colors as mplc
6
+ from matplotlib.figure import Figure
7
+ from matplotlib.gridspec import GridSpec
8
+ from anndata import AnnData
9
+ from pandas import CategoricalDtype
10
+ from scanpy.plotting.palettes import default_20, default_28, default_102
11
+
12
+ DEFAULT_CMAP = mplc.LinearSegmentedColormap.from_list("gray_blue_yellow", colors=["lightgray", "royalblue", "gold"])
13
+ DPI = 300
14
+
15
+ def set_categorical_colors(
16
+ adata: AnnData,
17
+ feature: str,
18
+ color_mapping: dict[str, str]
19
+ ):
20
+ """Set or override colors for a categorical observation column.
21
+
22
+ Parameters
23
+ ----------
24
+ adata
25
+ AnnData object containing the categorical column.
26
+ feature
27
+ Name of the categorical column in ``adata.obs``.
28
+ color_mapping
29
+ Mapping from category label to a Matplotlib-compatible color string.
30
+
31
+ Notes
32
+ -----
33
+ Colors are stored in ``adata.uns[f"{feature}_colors"]`` using the standard
34
+ Scanpy convention. Any categories not included in ``color_mapping`` keep their
35
+ existing colors or receive default Scanpy palette colors.
36
+ """
37
+ if feature not in adata.obs.columns:
38
+ raise ValueError(f"'{feature}' not found in adata.obs")
39
+ if not isinstance(adata.obs[feature].dtype, CategoricalDtype):
40
+ raise ValueError(
41
+ f"'{feature}' is not categorical data. Check that the column values "
42
+ + "are correct before casting to categorical")
43
+ if len(color_mapping) == 0:
44
+ print("No categories provided, no colors were changed.")
45
+ return
46
+ non_str_keys = [k for k in color_mapping.keys() if not isinstance(k, str)]
47
+ if len(non_str_keys) > 0:
48
+ raise TypeError(
49
+ "All keys in the colors dict must be strings. "
50
+ + "Categorical data that appears numeric, such as clusters, "
51
+ + "should be represented as a string: '0', '13', etc. Non-string keys found: "
52
+ + ", ".join(str(k) for k in non_str_keys)
53
+ )
54
+
55
+ cats = adata.obs[feature].cat.categories
56
+ nonexistant_keys = [k for k in color_mapping.keys() if k not in cats]
57
+ if len(nonexistant_keys) > 0:
58
+ raise ValueError(
59
+ "Some category keys were provided that aren't present in the categorical column: "
60
+ + ", ".join(k for k in nonexistant_keys)
61
+ )
62
+
63
+ missing_cats = [c for c in cats if c not in color_mapping]
64
+ if len(missing_cats) > 0:
65
+ print("Some colors were not provided, using previously set or default colors: " + ", ".join(missing_cats))
66
+
67
+ ckey = feature + "_colors"
68
+ _set_default_colors_categorical(adata, feature)
69
+ adata.uns[ckey] = [color_mapping.get(c, adata.uns[ckey][i]) for i, c in enumerate(cats)]
70
+
71
+
72
+ def _set_default_colors_categorical(
73
+ adata: AnnData,
74
+ feature: str,
75
+ ):
76
+ """Populate default category colors when Scanpy-style colors are missing."""
77
+ color_key = feature + "_colors"
78
+ if color_key not in adata.uns:
79
+ cats = adata.obs[feature].cat.categories
80
+ if len(cats) <= 20:
81
+ adata.uns[color_key] = default_20[:len(cats)]
82
+ elif len(cats) <= 28:
83
+ adata.uns[color_key] = default_28[:len(cats)]
84
+ elif len(cats) <= 102:
85
+ adata.uns[color_key] = default_102[:len(cats)]
86
+ else:
87
+ raise ValueError("Categorical column has more than 102 categories!")
88
+
89
+
90
+ def get_categorical_colormap(
91
+ adata: AnnData,
92
+ feature: str,
93
+ ) -> dict:
94
+ """Return the current category-to-color mapping for a categorical feature."""
95
+ color_key = feature + "_colors"
96
+ if color_key not in adata.uns:
97
+ raise ValueError(f"Color mapping for '{feature}' not present in adata.uns")
98
+ return dict(zip(adata.obs[feature].cat.categories, adata.uns[color_key]))
99
+
100
+
101
+ def subplots_with_side_axis(
102
+ fig: Figure,
103
+ nrows: int,
104
+ ncols: int,
105
+ side_ax_direction: Literal["horizontal", "vertical"],
106
+ side_ax_proportion: float,
107
+ ):
108
+ """Create a subplot grid with one extra shared axis for a legend or colorbar.
109
+
110
+ Parameters
111
+ ----------
112
+ fig
113
+ Figure that should receive the axes.
114
+ nrows, ncols
115
+ Grid shape for the main plotting axes.
116
+ side_ax_direction
117
+ Whether the extra axis should be appended below the grid or to its right.
118
+ side_ax_proportion
119
+ Fraction of the figure reserved for the extra axis.
120
+
121
+ Returns
122
+ -------
123
+ tuple[list[Axes], Axes]
124
+ The main axes in row-major order and the shared side axis.
125
+ """
126
+ # Prepare figure with 2x2 plots and one extra (for colorbar/legend)
127
+ if side_ax_direction == "horizontal":
128
+ gs = GridSpec(nrows+1, ncols, height_ratios=[(1 - side_ax_proportion)/nrows]*nrows + [side_ax_proportion])
129
+ axes = [fig.add_subplot(gs[i // ncols, i % ncols]) for i in range(nrows * ncols)]
130
+ side_ax = fig.add_subplot(gs[nrows, :]) # bottommost row
131
+ elif side_ax_direction == "vertical":
132
+ gs = GridSpec(nrows, ncols+1, width_ratios=[(1 - side_ax_proportion)/ncols]*ncols + [side_ax_proportion])
133
+ axes = [fig.add_subplot(gs[i // ncols, i % ncols]) for i in range(nrows * ncols)]
134
+ side_ax = fig.add_subplot(gs[:, ncols]) # bottommost row
135
+ else:
136
+ raise ValueError(f"Invalid value {side_ax_direction} for legend_loc")
137
+
138
+ return axes, side_ax
@@ -0,0 +1,232 @@
1
+ """Composition-style plots for summarizing categorical observations."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+ from matplotlib import pyplot as plt
7
+ from matplotlib.axes import Axes
8
+ from matplotlib.figure import Figure
9
+ from matplotlib.patheffects import withStroke
10
+ import numpy as np
11
+ from pandas import DataFrame, crosstab
12
+ from anndata import AnnData
13
+
14
+ from . import DPI, _set_default_colors_categorical, get_categorical_colormap, subplots_with_side_axis
15
+ from .legend import make_legend
16
+ from ..text import clean_title, rename
17
+
18
+ def graph_proportions(
19
+ adata: AnnData,
20
+ x: str,
21
+ y: str,
22
+ x_order: list | np.ndarray | None = None,
23
+ figsize: tuple[int, int] = (3, 6),
24
+ legend_proportion: float = 0.1,
25
+ x_tick_rotation: int = 0,
26
+ percentages_fontsize: int = 8,
27
+ percentages_color: str = "#000000",
28
+ percentages_outline_width: float = 0.5,
29
+ percentages_outline_color: str = "#dddddd",
30
+ percentages_decimal_places: int = 2,
31
+ percentages_display_threshold: float = 1,
32
+ color_override: dict[str, str] | None = None,
33
+ ) -> tuple[DataFrame, Figure, Axes, Axes]:
34
+ """Plot stacked percentages for one observation column across another.
35
+
36
+ Parameters
37
+ ----------
38
+ adata
39
+ AnnData object containing both observation columns.
40
+ x
41
+ Observation column used for the bar positions.
42
+ y
43
+ Observation column used for the stacked segments and legend entries.
44
+ x_order
45
+ Optional explicit order to apply before plotting.
46
+ figsize
47
+ Figure size passed to Matplotlib.
48
+ legend_proportion
49
+ Fraction of the figure width reserved for the side legend axis.
50
+ x_tick_rotation
51
+ Rotation angle for x-axis tick labels.
52
+ percentages_fontsize, percentages_color
53
+ Styling for the percentage labels drawn inside each bar segment.
54
+ percentages_outline_width, percentages_outline_color
55
+ Stroke styling that helps the percentage labels remain readable.
56
+ percentages_decimal_places
57
+ Number of decimal places to show. Only 0, 1, or 2 are accepted.
58
+ percentages_display_threshold
59
+ Segments at or below this percentage are left unlabeled.
60
+ color_override
61
+ Optional per-category color mapping that overrides stored colors for ``y``.
62
+
63
+ Returns
64
+ -------
65
+ tuple[DataFrame, Figure, Axes, Axes]
66
+ The percentage table and the created figure axes.
67
+ """
68
+ if percentages_decimal_places < 0 or percentages_decimal_places > 2:
69
+ raise ValueError("Can only display 0, 1, or 2 decimal places for percentages")
70
+ if x not in adata.obs.columns:
71
+ raise ValueError(f"'{x}' not in adata.obs")
72
+ if y not in adata.obs.columns:
73
+ raise ValueError(f"'{y}' not in adata.obs")
74
+ df = crosstab(adata.obs[x], adata.obs[y])
75
+ if x_order is not None:
76
+ df = df.loc[x_order, :]
77
+
78
+ fig = plt.figure(figsize=figsize, dpi=DPI)
79
+ axes, side_ax = subplots_with_side_axis(fig, 1, 1, "vertical", legend_proportion)
80
+ ax = axes[0]
81
+ # make percent
82
+ df = df.div(df.sum(axis=1), axis=0) * 100
83
+
84
+ bottom = np.zeros(len(df.index))
85
+
86
+ _set_default_colors_categorical(adata, y)
87
+ colormap = get_categorical_colormap(adata, y)
88
+ for ct in df.columns:
89
+ ax.bar(
90
+ df.index,
91
+ df[ct],
92
+ bottom = bottom,
93
+ label = ct,
94
+ color = color_override[ct] if color_override is not None else colormap[ct],
95
+ )
96
+
97
+ # place text in the middle of the bar segments showing the value
98
+ for i, i_x in enumerate(df.index):
99
+ height = float(df.loc[i_x, ct]) # pyright: ignore[reportArgumentType]
100
+ if height <= percentages_display_threshold:
101
+ continue
102
+ match percentages_decimal_places:
103
+ case 0: text = f"{height:.0f}%"
104
+ case 1: text = f"{height:.1f}%"
105
+ case 2: text = f"{height:.2f}%"
106
+ ax.text(
107
+ i_x,
108
+ bottom[i] + height/2,
109
+ text,
110
+ ha="center", va="center",
111
+ fontsize=percentages_fontsize,
112
+ color=percentages_color,
113
+ weight="bold",
114
+ path_effects=[withStroke(
115
+ linewidth=percentages_outline_width,
116
+ foreground=percentages_outline_color
117
+ )]
118
+ )
119
+
120
+ bottom += df[ct]
121
+
122
+ ax.set_ylim((0, 100))
123
+ ax.grid(False)
124
+ ax.set_ylabel("Percent of Cells")
125
+ ax.set_xlabel("")
126
+ locs, labels = plt.xticks()
127
+ for l in labels:
128
+ l.set_text(clean_title(rename(adata, l.get_text())))
129
+ ax.set_xticks(locs, labels, rotation=x_tick_rotation)
130
+ ax.tick_params(length=0)
131
+ ax.spines['top'].set_visible(False)
132
+ ax.spines['right'].set_visible(False)
133
+ ax.spines['bottom'].set_visible(False)
134
+
135
+ make_legend(
136
+ ax=side_ax,
137
+ label_color_dict=dict(reversed(colormap.items())),
138
+ title=clean_title(rename(adata, y)),
139
+ label_rename_dict={l: clean_title(rename(adata, l)) for l in colormap.keys()}
140
+ )
141
+ plt.tight_layout()
142
+ return df, fig, ax, side_ax
143
+
144
+ def graph_counts(
145
+ adata: AnnData,
146
+ hue: str,
147
+ x: str,
148
+ x_order: list | np.ndarray | None = None,
149
+ stack: bool = False,
150
+ sort_by_size: bool = True,
151
+ figsize=(6, 3),
152
+ legend_proportion: float = 0.1,
153
+ x_tick_rotation: int = 90,
154
+ legend_kwargs: dict[str, Any] | None = None
155
+ ) -> tuple[DataFrame, Figure, Axes, Axes]:
156
+ """Plot category counts as grouped or stacked bars.
157
+
158
+ Parameters
159
+ ----------
160
+ adata
161
+ AnnData object containing the observation columns.
162
+ hue
163
+ Observation column used for bar colors and legend entries.
164
+ x
165
+ Observation column used for the x-axis groups.
166
+ x_order
167
+ Optional explicit order to apply before plotting when size-based sorting is
168
+ disabled.
169
+ stack
170
+ If ``True``, stack the category bars instead of placing them side by side.
171
+ sort_by_size
172
+ If ``True``, order groups by total count before plotting.
173
+ figsize
174
+ Figure size passed to Matplotlib.
175
+ legend_proportion
176
+ Fraction of the figure width reserved for the side legend axis.
177
+ x_tick_rotation
178
+ Rotation angle for x-axis tick labels.
179
+ legend_kwargs
180
+ Extra keyword arguments forwarded to :func:`make_legend`.
181
+
182
+ Returns
183
+ -------
184
+ tuple[DataFrame, Figure, Axes, Axes]
185
+ The count table and the created figure axes.
186
+ """
187
+ if x not in adata.obs.columns:
188
+ raise ValueError(f"'{x}' not in adata.obs")
189
+ if hue not in adata.obs.columns:
190
+ raise ValueError(f"'{hue}' not in adata.obs")
191
+ df = crosstab(adata.obs[x], adata.obs[hue])
192
+ if sort_by_size:
193
+ df = df.assign(total=lambda c: c.sum(axis=1))
194
+ df = df.sort_values("total", ascending=False)
195
+ df = df.drop(columns="total")
196
+ elif x_order is not None:
197
+ df = df.loc[x_order, :]
198
+
199
+ _set_default_colors_categorical(adata, hue)
200
+ colormap = get_categorical_colormap(adata, hue)
201
+ fig = plt.figure(figsize=figsize)
202
+ axes, side_ax = subplots_with_side_axis(fig, 1, 1, "vertical", legend_proportion)
203
+ ax = axes[0]
204
+ df.plot.bar(figsize=figsize, stacked=stack, color=colormap, ax=ax, legend=False)
205
+
206
+ fig = ax.get_figure()
207
+ if fig is not None:
208
+ fig.set_dpi(DPI)
209
+ ax.set_axisbelow(True)
210
+ ax.grid(axis="y")
211
+ ax.set_ylabel("Number of Cells")
212
+ ax.set_xlabel(clean_title(rename(adata, x)))
213
+ ax.set_xticks(
214
+ range(len(df.index)),
215
+ [clean_title(rename(adata, l)) for l in df.index],
216
+ rotation=x_tick_rotation,
217
+ )
218
+ ax.spines['top'].set_visible(False)
219
+ ax.spines['right'].set_visible(False)
220
+
221
+ if legend_kwargs is None:
222
+ legend_kwargs = dict()
223
+ make_legend(
224
+ ax=side_ax,
225
+ label_color_dict=colormap,
226
+ title=clean_title(rename(adata, hue)),
227
+ label_rename_dict={l: clean_title(rename(adata, l)) for l in colormap.keys()},
228
+ **legend_kwargs
229
+ )
230
+
231
+ plt.tight_layout()
232
+ return df, fig, ax, side_ax
@@ -0,0 +1,145 @@
1
+ from __future__ import annotations
2
+
3
+ from matplotlib import pyplot as plt
4
+ from matplotlib.axes import Axes
5
+ from matplotlib.cm import ScalarMappable
6
+ from matplotlib.lines import Line2D
7
+ from matplotlib.colorbar import Colorbar
8
+ from matplotlib.legend import Legend
9
+ import numpy as np
10
+ import numpy.typing as npt
11
+ import textwrap
12
+
13
+ def make_colorbar(
14
+ sm: ScalarMappable,
15
+ cax: Axes,
16
+ label: str,
17
+ ticks: npt.ArrayLike | None = None,
18
+ vmin: float | None = None,
19
+ vmax: float | None = None,
20
+ vcenter: float | None = None,
21
+ label_fontsize: float = 14,
22
+ tick_fontsize: float = 10,
23
+ **kwargs
24
+ ) -> Colorbar:
25
+ """Draw a colorbar with consistent labeling and endpoint tick handling.
26
+
27
+ Parameters
28
+ ----------
29
+ sm
30
+ Scalar mappable used to generate the color scale.
31
+ cax
32
+ Axes that should contain the colorbar.
33
+ label
34
+ Text label shown alongside the colorbar.
35
+ ticks
36
+ Optional explicit tick locations. If omitted, ticks are inferred from the
37
+ colorbar and adjusted so the upper endpoint is labeled cleanly.
38
+ vmin, vmax, vcenter
39
+ Data range used by the colorbar. ``vcenter`` is accepted for API
40
+ compatibility with callers, although the norm should already be encoded on
41
+ ``sm``.
42
+ label_fontsize
43
+ Font size for the colorbar label.
44
+ tick_fontsize
45
+ Font size for tick labels.
46
+ **kwargs
47
+ Additional keyword arguments forwarded to ``matplotlib.pyplot.colorbar``.
48
+ """
49
+ cbar = plt.colorbar(sm, cax=cax, **kwargs)
50
+ cbar.set_label(label, fontsize=label_fontsize)
51
+ cbar.ax.tick_params(labelsize=tick_fontsize)
52
+ if ticks is not None:
53
+ cbar.set_ticks(np.asarray(ticks, dtype=float).tolist())
54
+ elif vmin is not None and vmax is not None:
55
+ inferred_ticks = list(cbar.get_ticks())
56
+ if len(inferred_ticks) >= 3:
57
+ # Remove the last tick if it is too close to the maximum value to avoid
58
+ # overlapping endpoint labels.
59
+ if vmax - inferred_ticks[-2] < (inferred_ticks[-2] - inferred_ticks[-3]) / 4:
60
+ inferred_ticks = inferred_ticks[:-2] + [vmax]
61
+ else:
62
+ inferred_ticks = inferred_ticks[:-1] + [vmax]
63
+ cbar.set_ticks(inferred_ticks, labels=[f"{tick:.2f}" for tick in inferred_ticks])
64
+ if vmin is not None and vmax is not None:
65
+ cbar.ax.set_ylim(vmin, vmax)
66
+ return cbar
67
+
68
+
69
+ def make_legend(
70
+ ax: Axes,
71
+ title: str,
72
+ label_color_dict: dict,
73
+ sort_ints: bool = True,
74
+ label_rename_dict: dict | None = None,
75
+ loc: str = "center left",
76
+ markersize: float = 6,
77
+ fontsize: int = 12,
78
+ title_fontsize: int = 14,
79
+ text_wrap_chars: int | None = 15,
80
+ ) -> Legend:
81
+ """Draw a simple square-marker legend on a dedicated axis.
82
+
83
+ Parameters
84
+ ----------
85
+ ax
86
+ Axis that should contain only the legend.
87
+ title
88
+ Legend title.
89
+ label_color_dict
90
+ Mapping from category label to marker color.
91
+ sort_ints
92
+ Sort labels numerically when they look like integers.
93
+ label_rename_dict
94
+ Optional display-name overrides for legend labels.
95
+ loc
96
+ Matplotlib legend location string.
97
+ markersize
98
+ Size of the square legend markers.
99
+ fontsize
100
+ Font size for legend labels.
101
+ title_fontsize
102
+ Font size for the legend title.
103
+ text_wrap_chars
104
+ Optional wrap width applied to the title.
105
+
106
+ Returns
107
+ -------
108
+ matplotlib.legend.Legend
109
+ The created legend object.
110
+ """
111
+ label_order = list(label_color_dict.keys())
112
+ if sort_ints:
113
+ try:
114
+ label_order = sorted(label_order, key=int, reverse=True) # reverse = True so integers increase from the bottom
115
+ except (TypeError, ValueError):
116
+ pass
117
+
118
+ if label_rename_dict is None:
119
+ label_rename_dict = {k: k for k in label_color_dict.keys()}
120
+ else:
121
+ label_rename_dict = {k: k for k in label_color_dict.keys()} | label_rename_dict
122
+ handles = [
123
+ Line2D([], [], marker='s', linestyle='None', color=label_color_dict[label],
124
+ label=label_rename_dict[label], markersize=markersize)
125
+ for label in label_order
126
+ ]
127
+
128
+ if text_wrap_chars is not None:
129
+ title = textwrap.fill(title, text_wrap_chars)
130
+
131
+ legend = ax.legend(
132
+ handles=handles,
133
+ title = title,
134
+ loc = loc,
135
+ fontsize = fontsize,
136
+ title_fontsize = title_fontsize
137
+ )
138
+ legend.get_title().set_multialignment('center')
139
+ ax.set_facecolor('none') # No background color
140
+ ax.set_xticks([])
141
+ ax.set_yticks([])
142
+ for spine in ax.spines.values():
143
+ spine.set_visible(False)
144
+ ax.patch.set_alpha(0)
145
+ return legend