# Load spatial mouse data
import scanpy as sc
# Load the actual spatial mouse data
spatial_mouse_data = sc.read_h5ad('/data/analysis/data_mcandrew/00_allos_0.6_TAB/data/mouse_cbs/mouse_sit/cbs1/iso.quant.h5ad')
# 1) New column with just the ENS transcript IDs
spatial_mouse_data.var["transcriptId"] = spatial_mouse_data.var["transcript_id"]
# 2) Rename gene_symbol → geneId
spatial_mouse_data.var = spatial_mouse_data.var.rename(columns={"gene_symbol": "geneId"})
spatial_mouse_data.var.index = spatial_mouse_data.var["transcriptId"]
# Rename spatial coordinates to X_spatial for consistency
if "spatial" in spatial_mouse_data.obsm:
spatial_mouse_data.obsm["X_spatial"] = spatial_mouse_data.obsm["spatial"]
print(spatial_mouse_data)
print(f"Spatial coordinates shape: {spatial_mouse_data.obsm['X_spatial'].shape}")Coordinate Plots
calculate_density
def calculate_density(
adata, # Annotated data object
feature:str, # Feature name (e.g., transcript ID)
basis:str='umap', # Embedding basis (e.g., 'umap', 'spatial')
coord_key:Optional[str]=None, # Override for coordinate key in obsm
adjust:float=1.0, # Bandwidth adjustment for KDE
map_to_cells:bool=True, # If True, return density values for each cell
n:int=200, # Grid resolution for density calculation
lims:NoneType=None, # Coordinate limits [xmin, xmax, ymin, ymax]
)->np.ndarray: # Density values (per cell if map_to_cells=True, else grid)
Calculate weighted KDE-based spatial density for a feature.
get_dens
def get_dens(
points, # Points array (n_cells, 2)
dens, # Dictionary with 'x', 'y', 'z' from wkde2d
): # Density values at each point
Map each 2D point to the approximate density in dens[“z”].
wkde2d
def wkde2d(
x, y, w:NoneType=None, # Weights (same length as x, y). If None, uniform weights.
h:NoneType=None, # Bandwidth(s). If None, use Scott's rule.
adjust:float=1.0, # Bandwidth multiplier
n:int=100, # Number of grid points per axis
lims:NoneType=None, # [xmin, xmax, ymin, ymax]
): # Dictionary with keys 'x', 'y', 'z' (grid coordinates and density)
Weighted 2D KDE.
plot_coords_standalone
def plot_coords_standalone(
coords:np.ndarray, # Coordinates array (n_cells, 2)
values:np.ndarray, # Values array (n_features, n_cells) or (n_cells,)
titles:Optional[List[str]]=None, # Title for each panel
cmaps:Optional[List[str]]=None, # Colormap for each panel
max_cols:int=2, # Maximum columns in grid
size:float=5.0, # Point size
alpha:float=0.9, # Point alpha
vmin:Optional[float]=None, vmax:Optional[float]=None,
use_per_panel_scale:bool=False, # If True, each panel has its own colorbar scale based on its own data.
If False (default), all panels share a global scale.
axis_labels:Tuple[str, str]=('x', 'y'), # Labels for x and y axes
show_colorbar:bool=True, # Whether to show colorbar
fig_width:float=12.0, # Figure width in inches
fig_height:Optional[float]=None, # Figure height in inches (auto if None)
)->plt.Figure: # The figure object
Standalone coordinate plot with multiple panels.
get_expression_from_adata
def get_expression_from_adata(
adata, features:List[str]
)->np.ndarray:
Extract expression values for specified features from AnnData.
get_coords_from_adata
def get_coords_from_adata(
adata, basis:str='umap', coord_key:Optional[str]=None
)->np.ndarray:
Extract 2D coordinates from AnnData.
API reference
plot_transcript_umap
def plot_transcript_umap(
adata, # Annotated data object
transcripts:Optional[List[str]]=None, # Explicit list of transcript IDs to plot
gene_id:Optional[str]=None, # Gene ID to get top transcripts from
top_n:int=2, # Number of top transcripts to select (when using gene_id)
group_col:Optional[str]=None, # Column in adata.obs for grouping (required when using gene_id)
estimator:str='pseudobulk', # Estimator for PSI calculation ('pseudobulk' or 'mean')
dirichlet_alpha:float=0.5, # Dirichlet alpha for pseudobulk estimation
epsilon:float=1e-06, # Small value to avoid division by zero
basis:str='umap', # Embedding basis (default: 'umap')
cmaps:Optional[List[str]]=None, # Colormap for each transcript (default: viridis variants)
max_cols:int=2, # Maximum number of columns in grid
size:float=5.0, # Point size
alpha:float=0.9, # Point alpha
vmin:Optional[float]=None, vmax:Optional[float]=None,
use_global_vmin_vmax:bool=True, # If True, use global min/max across all transcripts
show_colorbar:bool=True, # If True, add colorbar to each subplot
fig_width:float=12.0, # Figure width in inches
fig_height:Optional[float]=None, # Figure height in inches (auto if None)
)->plt.Figure: # The matplotlib figure
Plot transcript expression on UMAP embedding (scanpy-like API).
Provide either explicit transcripts OR gene_id + top_n to automatically select the most variable isoforms.
plot_umap_density
def plot_umap_density(
adata, # Annotated data object
transcripts:Optional[List[str]]=None, # Explicit list of transcript IDs to plot
gene_id:Optional[str]=None, # Gene ID to get top transcripts from
top_n:int=2, # Number of top transcripts to select (when using gene_id)
group_col:Optional[str]=None, # Column in adata.obs for grouping (required when using gene_id)
estimator:str='pseudobulk', # Estimator for PSI calculation ('pseudobulk' or 'mean')
dirichlet_alpha:float=0.5, # Dirichlet alpha for pseudobulk estimation
epsilon:float=1e-06, # Small value to avoid division by zero
basis:str='umap', # Embedding basis (default: 'umap')
adjust:float=1.0, # Bandwidth adjustment for KDE
cmaps:Optional[List[str]]=None, # Colormap for each transcript (default: Reds variants)
max_cols:int=2, # Maximum number of columns in grid
size:float=5.0, # Point size
alpha:float=0.9, # Point alpha
vmin:Optional[float]=None, vmax:Optional[float]=None,
use_per_panel_scale:bool=True, # If True (default), each panel has its own colorbar scale.
If False, all panels share a global scale.
show_colorbar:bool=True, # If True, add colorbar to each subplot
fig_width:float=12.0, # Figure width in inches
fig_height:Optional[float]=None, # Figure height in inches (auto if None)
)->plt.Figure: # The matplotlib figure
Plot transcript spatial density (KDE) on UMAP embedding (scanpy-like API).
Provide either explicit transcripts OR gene_id + top_n to automatically select the most variable isoforms.
plot_transcript_spatial
def plot_transcript_spatial(
adata, # Annotated data object
transcripts:Optional[List[str]]=None, # Explicit list of transcript IDs to plot
gene_id:Optional[str]=None, # Gene ID to get top transcripts from
top_n:int=2, # Number of top transcripts to select (when using gene_id)
group_col:Optional[str]=None, # Column in adata.obs for grouping (required when using gene_id)
estimator:str='pseudobulk', # Estimator for PSI calculation ('pseudobulk' or 'mean')
dirichlet_alpha:float=0.5, # Dirichlet alpha for pseudobulk estimation
epsilon:float=1e-06, # Small value to avoid division by zero
basis:str='spatial', # Embedding basis (default: 'spatial')
cmaps:Optional[List[str]]=None, # Colormap for each transcript (default: viridis variants)
max_cols:int=2, # Maximum number of columns in grid
size:float=5.0, # Point size
alpha:float=0.9, # Point alpha
vmin:Optional[float]=None, vmax:Optional[float]=None,
use_global_vmin_vmax:bool=True, # If True, use global min/max across all transcripts
show_colorbar:bool=True, # If True, add colorbar to each subplot
fig_width:float=12.0, # Figure width in inches
fig_height:Optional[float]=None, # Figure height in inches (auto if None)
invert_y:bool=True, # If True, invert y-axis (default: True for spatial plots)
)->plt.Figure: # The matplotlib figure
Plot transcript expression on spatial coordinates (scanpy-like API).
Provide either explicit transcripts OR gene_id + top_n to automatically select the most variable isoforms.
plot_spatial_density
def plot_spatial_density(
adata, # Annotated data object
transcripts:Optional[List[str]]=None, # Explicit list of transcript IDs to plot
gene_id:Optional[str]=None, # Gene ID to get top transcripts from
top_n:int=2, # Number of top transcripts to select (when using gene_id)
group_col:Optional[str]=None, # Column in adata.obs for grouping (required when using gene_id)
estimator:str='pseudobulk', # Estimator for PSI calculation ('pseudobulk' or 'mean')
dirichlet_alpha:float=0.5, # Dirichlet alpha for pseudobulk estimation
epsilon:float=1e-06, # Small value to avoid division by zero
basis:str='spatial', # Embedding basis (default: 'spatial')
adjust:float=1.0, # Bandwidth adjustment for KDE
cmaps:Optional[List[str]]=None, # Colormap for each transcript (default: Reds variants)
max_cols:int=2, # Maximum number of columns in grid
size:float=5.0, # Point size
alpha:float=0.9, # Point alpha
vmin:Optional[float]=None, vmax:Optional[float]=None,
use_per_panel_scale:bool=True, # If True (default), each panel has its own colorbar scale.
If False, all panels share a global scale.
show_colorbar:bool=True, # If True, add colorbar to each subplot
fig_width:float=12.0, # Figure width in inches
fig_height:Optional[float]=None, # Figure height in inches (auto if None)
invert_y:bool=True, # If True, invert y-axis (default: True for spatial plots)
)->plt.Figure: # The matplotlib figure
Plot transcript spatial density (KDE) on spatial coordinates (scanpy-like API).
Provide either explicit transcripts OR gene_id + top_n to automatically select the most variable isoforms.
plot_coords_from_adata
def plot_coords_from_adata(
adata, # Annotated data object
features:List[str], # Feature names (transcript IDs, gene names, etc.)
basis:str='umap', # Embedding basis (e.g., 'umap', 'tsne')
coord_key:Optional[str]=None, # Override for coordinate key in obsm
cmaps:Optional[List[str]]=None, # Colormap for each feature
max_cols:int=2, # Maximum number of columns in grid
size:float=5.0, # Point size
alpha:float=0.9, # Point alpha
vmin:Optional[float]=None, vmax:Optional[float]=None,
use_global_vmin_vmax:bool=True, # If True, use global min/max across all features
axis_labels:Optional[Tuple[str, str]]=None, # Labels for x and y axes (default: based on basis)
show_colorbar:bool=True, # If True, add colorbar to each subplot
fig_width:float=12.0, # Figure width in inches
fig_height:Optional[float]=None, # Figure height in inches (auto if None)
)->Tuple[plt.Figure, np.ndarray, np.ndarray]: # The figure object
Plot coordinates from AnnData for multiple features.
Scanpy-like API Examples
Demonstration of plot_transcript_umap() and plot_umap_density()
Spatial Plot Examples
Demonstration of plot_transcript_spatial() and plot_spatial_density()