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
82 changes: 39 additions & 43 deletions src/spac/templates/histogram_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"""
import json
import sys
import warnings
from pathlib import Path
from typing import Any, Dict, Union, Optional, Tuple, List
import pandas as pd
Expand Down Expand Up @@ -305,19 +306,24 @@ def run_from_json(
hist_kwargs["facet_fig_height"] = fig_height
hist_kwargs["facet_tick_rotation"] = x_rotate

result = histogram(
adata=adata,
feature=feature,
annotation=annotation,
layer=text_to_value(layer, "Original"),
group_by=group_by,
together=together,
ax=None,
x_log_scale=take_X_log,
y_log_scale=take_Y_log,
facet=facet,
**hist_kwargs,
)
with warnings.catch_warnings(record=True) as caught_warnings:
warnings.simplefilter("always")
result = histogram(
adata=adata,
feature=feature,
annotation=annotation,
layer=text_to_value(layer, "Original"),
group_by=group_by,
together=together,
ax=None,
x_log_scale=take_X_log,
y_log_scale=take_Y_log,
facet=facet,
**hist_kwargs,
)
for warning in caught_warnings:
if issubclass(warning.category, UserWarning):
logger.warning(str(warning.message))

fig = result["fig"]
axs = result["axs"]
Expand Down Expand Up @@ -367,37 +373,27 @@ def run_from_json(
label.set_rotation_mode('anchor')
label.set_horizontalalignment('right')

# Set titles based on group_by and facet
if text_to_value(group_by):
if together:
for ax in axes:
ax.set_title(
f'Histogram of "{x_var}" grouped by "{group_by}"'
)
else:
# compute unique groups directly from adata.obs.
unique_groups = adata.obs[
text_to_value(group_by)
].dropna().unique()
if len(axes) != len(unique_groups):
logger.warning(
"Number of axes does not match number of "
"groups. Titles may not correspond correctly."
)
if facet:
fig.suptitle(
f'Histogram of "{x_var}" faceted by "{group_by}"'
)
ax_title_prefix = f'Group'
else:
ax_title_prefix = f'Histogram of "{x_var}" for group'
for ax, grp in zip(axes, unique_groups):
ax.set_title(
f'{ax_title_prefix}: "{grp}"'
)
# Set figure-level titles base on data type, table and group_by.
# 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})'
)
if len(axes) == 1:
axes[0].set_title(histogram_title)
else:
for ax in axes:
ax.set_title(f'Count plot of "{x_var}"')
fig.suptitle(histogram_title)

# Adjust layout to prevent title overlap
if facet:
Expand Down
73 changes: 56 additions & 17 deletions src/spac/visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,9 +499,11 @@ def histogram(adata, feature=None, annotation=None, layer=None,

When `group_by` is provided, this optional key can be passed via
`kwargs` (it is ignored otherwise):
- `max_groups`: Controls the group-count guardrail for grouped plots.
- `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.

When `facet=True`, these optional keys can be passed via `kwargs`
to customize FacetGrid layout (they are ignored otherwise):
Expand All @@ -524,6 +526,8 @@ def histogram(adata, feature=None, annotation=None, layer=None,

df : pandas.DataFrame
DataFrame containing the data used for plotting the histogram.
When groups are filtered, ``df.attrs['spac_histogram_filter']``
contains the displayed and original group counts.

"""

Expand Down Expand Up @@ -635,6 +639,10 @@ def cal_bin_num(
# Parse max_groups only for grouped plots; otherwise ignore it entirely.
if group_by:
max_groups = 20 if max_groups_raw is None else max_groups_raw
if max_groups <= 0:
raise ValueError(
f'`max_groups` should be a positive integer. Received "{max_groups}".'
)
else:
max_groups = None

Expand Down Expand Up @@ -798,21 +806,44 @@ def resolve_hist_axis_labels(data_column, x_log_scale, y_log_scale, stat):

# Dispatch to grouped-together, grouped-separate, faceted, or
# ungrouped plotting.
filter_metadata = None
if group_by:
groups = df[group_by].dropna().unique().tolist()
groups = plot_data[group_by].dropna().unique().tolist()
n_groups = len(groups)

if n_groups == 0:
raise ValueError("There must be at least one group to create a"
" histogram.")
elif n_groups > max_groups:
raise ValueError(
"The number of groups in `group_by` exceeds `max_groups`: "
f"found {n_groups}, threshold {max_groups}.\n"
"Please reduce/bucket groups or use another grouping column, or "
"pass a larger `max_groups`.\n"
"See `kwargs` documentation for more details."
# Filter plot_data to the `max_groups` most frequent groups
group_counts = plot_data[group_by].value_counts(
sort=False
).reindex(groups)
groups = group_counts.sort_values(
ascending=False,
kind='mergesort',
).head(max_groups).index.tolist()
plot_data = plot_data[plot_data[group_by].isin(groups)]

# Emit a warning about the group filtering
omitted_count = n_groups - max_groups
omitted_label = "group" if omitted_count == 1 else "groups"
warning_message = (
f'The number of groups in "{group_by}" exceeds "max_groups": '
f'found "{n_groups}", threshold "{max_groups}". '
f'Plotting the {max_groups} most frequent groups and '
f'omitting {omitted_count} {omitted_label}.'
)
warnings.warn(warning_message, UserWarning)

# Store metadata about the filtering for downstream use
filter_metadata = {
"filtered": True,
"shown": max_groups,
"total": n_groups,
"group_by": group_by,
}
n_groups = len(groups)

if together:
# 1) Grouped together on the same axes
Expand Down Expand Up @@ -844,9 +875,16 @@ def resolve_hist_axis_labels(data_column, x_log_scale, y_log_scale, stat):
**kwargs,
)

# If plotting feature specify which layer
if feature:
ax.set_title(f'Layer: {layer}')
ax.set_title(
f'Histogram of "{data_column}" (table: "{layer}") '
f'grouped by "{group_by}"'
)
else:
ax.set_title(
f'Histogram of annotation "{data_column}" grouped by '
f'"{group_by}"'
)
axs.append(ax)

else:
Expand Down Expand Up @@ -874,11 +912,7 @@ def resolve_hist_axis_labels(data_column, x_log_scale, y_log_scale, stat):
sns.histplot(data=hist_data, x="bin_center", ax=ax_i,
weights='count', **kwargs)

# If plotting feature specify which layer
if feature:
ax_i.set_title(f'{groups[i]} with Layer: {layer}')
else:
ax_i.set_title(f'{groups[i]}')
ax_i.set_title(f'{groups[i]}')
axs.append(ax_i)

else:
Expand Down Expand Up @@ -977,9 +1011,10 @@ def resolve_hist_axis_labels(data_column, x_log_scale, y_log_scale, stat):
**kwargs
)

# If plotting feature specify which layer
ax_title = f'Histogram of "{data_column}"'
if feature:
ax.set_title(f'Layer: {layer}')
ax_title += f' (table: "{layer}")'
ax.set_title(ax_title)
axs.append(ax)

# Determine axis labels based on scale and stat settings.
Expand Down Expand Up @@ -1009,6 +1044,10 @@ def resolve_hist_axis_labels(data_column, x_log_scale, y_log_scale, stat):
fig.supxlabel(xlabel)
fig.supylabel(ylabel)

# Add metadata to the histogram DataFrame if groups were filtered
if filter_metadata is not None:
hist_data.attrs["spac_histogram_filter"] = filter_metadata

if len(axs) == 1:
return {"fig": fig, "axs": axs[0], "df": hist_data}
else:
Expand Down
Loading