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
42 changes: 26 additions & 16 deletions src/spac/templates/histogram_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ def run_from_json(
dict or tuple
If save_to_disk=True: Dictionary of saved file paths
If save_to_disk=False: Tuple of (figure, dataframe)

Notes
-----
If ``Group_by`` has more than ``Max_Groups`` groups (default 20), only
the ``Max_Groups`` most frequent groups are plotted. This filtering is
indicated in the default title.
"""
# Set up logging
logging.basicConfig(level=logging.INFO)
Expand Down Expand Up @@ -100,6 +106,7 @@ def run_from_json(
group_by = text_to_value(params.get("Group_by", "None"))
max_groups = params.get("Max_Groups", 20)
together = params.get("Together", True)
fig_title = text_to_value(params.get("Figure_Title"))
fig_width = params.get("Figure_Width", "auto")
fig_height = params.get("Figure_Height", "auto")
font_size = params.get("Font_Size", 12)
Expand Down Expand Up @@ -373,23 +380,26 @@ def run_from_json(
label.set_rotation_mode('anchor')
label.set_horizontalalignment('right')

# Set figure-level titles base on data type, table and group_by.
# Set the overall Histogram title.
# Multi-axis panel titles are handled by core as it may filter groups.
histogram_title = f'Histogram of "{x_var}"'
if feature:
layer = text_to_value(layer, "Original")
if layer:
histogram_title += f' (table: "{layer}")'
if group_by:
organizing_label = "faceted by" if facet else "grouped by"
histogram_title += f' {organizing_label} "{group_by}"'
filter_metadata = df_counts.attrs.get("spac_histogram_filter", {})
if filter_metadata.get("filtered"):
filter_label = "facets" if facet else "groups"
histogram_title += (
f' (top {filter_metadata["shown"]} of '
f'{filter_metadata["total"]} {filter_label})'
)
histogram_title = fig_title
if histogram_title is None:
# Generate the default title from the plot and filtering settings.
histogram_title = f'Histogram of "{x_var}"'
if feature:
layer = text_to_value(layer, "Original")
if layer:
histogram_title += f' (table: "{layer}")'
if group_by:
organizing_label = "faceted by" if facet else "grouped by"
histogram_title += f'\n{organizing_label} "{group_by}"'
filter_metadata = df_counts.attrs.get("spac_histogram_filter", {})
if filter_metadata.get("filtered"):
filter_label = "facets" if facet else "groups"
histogram_title += (
f' (top {filter_metadata["shown"]} of '
f'{filter_metadata["total"]} {filter_label})'
)
if len(axes) == 1:
axes[0].set_title(histogram_title)
else:
Expand Down
5 changes: 3 additions & 2 deletions src/spac/visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,8 +502,9 @@ def histogram(adata, feature=None, annotation=None, layer=None,
- `max_groups`: Controls the group-count filter for grouped plots.
Pass a positive integer, or omit it to use the default threshold
of 20 groups.
If the number of groups exceeds this threshold, only the most
frequent groups are plotted and a warning is emitted.
If the number of groups exceeds this threshold, only the
`max_groups` most frequent groups are plotted and a warning
is emitted.

When `facet=True`, these optional keys can be passed via `kwargs`
to customize FacetGrid layout (they are ignored otherwise):
Expand Down
82 changes: 70 additions & 12 deletions tests/templates/test_histogram_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ def _make_tiny_adata() -> ad.AnnData:
obs = pd.DataFrame({
"cell_type": ["A", "B", "A", "B"],
"batch": ["X", "X", "Y", "Y"],
})
}, index=["cell_0", "cell_1", "cell_2", "cell_3"])
var = pd.DataFrame(index=["Gene_0", "Gene_1"])
return ad.AnnData(X=X, obs=obs, var=var)
adata = ad.AnnData(X=X, obs=obs, var=var)
adata.layers["transformed"] = X.copy()
return adata


class TestHistogramTemplate(unittest.TestCase):
Expand All @@ -55,7 +57,6 @@ def setUp(self) -> None:
"Annotation": "cell_type",
"Table_to_Visualize": "Original",
"Feature_s_to_Plot": ["All"],
"Figure_Title": "Test Histogram",
"Legend_Title": "Cell Type",
"Figure_Width": 6,
"Figure_Height": 4,
Expand Down Expand Up @@ -133,7 +134,8 @@ def test_histogram_title_variants(self) -> None:
)
self.assertEqual(
fig._suptitle.get_text(),
'Histogram of "cell_type" faceted by "batch"',
'Histogram of "cell_type"\n'
'faceted by "batch"',
)

fig, _ = self._run_with_params(
Expand All @@ -147,7 +149,8 @@ def test_histogram_title_variants(self) -> None:
)
self.assertEqual(
fig.axes[0].get_title(),
'Histogram of "Gene_0" grouped by "cell_type"',
'Histogram of "Gene_0"\n'
'grouped by "cell_type"',
)

fig, _ = self._run_with_params(
Expand All @@ -160,7 +163,8 @@ def test_histogram_title_variants(self) -> None:
)
self.assertEqual(
fig.axes[0].get_title(),
'Histogram of "cell_type" grouped by "batch"',
'Histogram of "cell_type"\n'
'grouped by "batch"',
)

fig, _ = self._run_with_params(
Expand All @@ -173,7 +177,23 @@ def test_histogram_title_variants(self) -> None:
)
self.assertEqual(
fig._suptitle.get_text(),
'Histogram of "cell_type" grouped by "batch"',
'Histogram of "cell_type"\n'
'grouped by "batch"',
)

def test_grouped_feature_title_includes_named_table(self) -> None:
"""Keep the named table and grouping on separate title lines."""
fig, _ = self._run_with_params(
Plot_By="Feature",
Feature="Gene_0",
Table_="transformed",
Group_by="cell_type",
Together=True,
)
self.assertEqual(
fig.axes[0].get_title(),
'Histogram of "Gene_0" (table: "transformed")\n'
'grouped by "cell_type"',
)

def test_filtered_histogram_titles_include_suffixes(self) -> None:
Expand All @@ -189,8 +209,8 @@ def test_filtered_histogram_titles_include_suffixes(self) -> None:
)
self.assertEqual(
fig.axes[0].get_title(),
'Histogram of "cell_type" grouped by "batch" '
'(top 1 of 2 groups)',
'Histogram of "cell_type"\n'
'grouped by "batch" (top 1 of 2 groups)',
)

fig, _ = self._run_with_params(
Expand All @@ -203,8 +223,8 @@ def test_filtered_histogram_titles_include_suffixes(self) -> None:
)
self.assertEqual(
fig.axes[0].get_title(),
'Histogram of "cell_type" faceted by "batch" '
'(top 1 of 2 facets)',
'Histogram of "cell_type"\n'
'faceted by "batch" (top 1 of 2 facets)',
)

def test_unfiltered_histogram_titles_omit_suffix(self) -> None:
Expand All @@ -221,9 +241,47 @@ def test_unfiltered_histogram_titles_omit_suffix(self) -> None:
)
self.assertEqual(
fig.axes[0].get_title(),
'Histogram of "cell_type" grouped by "batch"',
'Histogram of "cell_type"\n'
'grouped by "batch"',
)

def test_custom_title_replaces_grouped_title(self) -> None:
"""A custom title is used for a grouped figure."""
fig, _ = self._run_with_params(
Plot_By="Feature",
Feature="Gene_0",
Group_by="cell_type",
Together=True,
Max_Groups=1,
Figure_Title="My histogram",
)
self.assertEqual(fig.axes[0].get_title(), "My histogram")

def test_custom_title_replaces_faceted_figure_title(self) -> None:
"""A custom title is used for a figure with multiple facets."""
fig, _ = self._run_with_params(
Plot_By="Annotation",
Annotation="cell_type",
Group_by="batch",
Together=False,
Facet=True,
Figure_Title="My faceted histogram",
)
self.assertEqual(fig._suptitle.get_text(), "My faceted histogram")

def test_none_like_custom_title_uses_generated_title(self) -> None:
"""None-like figure titles fall back to the default title."""
for title in (None, "None", "", " "):
with self.subTest(title=title):
fig, _ = self._run_with_params(
Plot_By="Feature",
Feature="Gene_0",
Figure_Title=title,
)
self.assertEqual(
fig.axes[0].get_title(), 'Histogram of "Gene_0"'
)


if __name__ == "__main__":
unittest.main()