Plotting (sdq.pl)#
sdq.pl.velocity_stream
- scdiffeq.plotting._velocity_stream.velocity_stream(adata: AnnData, ax: Axes | List[Axes] | None = None, c: str = 'dodgerblue', cmap: Dict | List | Tuple | None = 'plasma_r', group_zorder: Dict | None = None, linewidth: float = 0.5, stream_density: float = 2.5, add_margin: float = 0.1, arrowsize: float = 1, arrowstyle: str = '-|>', maxlength: float = 4, integration_direction: str = 'both', scatter_zorder: int = 101, stream_zorder: int = 201, density: float = 1, smooth: float = 0.5, n_neighbors: int | None = None, min_mass: float = 1, autoscale=True, stream_adjust=True, cutoff_percentile: float = 0.05, velocity_key: str = 'velocity', self_transitions: bool = True, use_negative_cosines: bool = True, T_scale: float = 10, disable_scatter: bool = False, disable_cbar: bool = False, stream_kwargs: Dict[str, Any] | None = {}, scatter_kwargs: Dict[str, Any] | None = {}, cbar_kwargs: Dict | None = {}, mpl_kwargs: Dict[str, Any] | None = {}, return_axes: bool = False, save: bool | None = False, rasterized: bool = True, png_dpi: float | None = 500, svg_dpi: float | None = 250, *args, **kwargs) List[Axes] | None[source]
Generates velocity stream plots for single-cell data using the VelocityStreamPlot class.
This function is a convenient wrapper around the VelocityStreamPlot class, allowing users to quickly generate and customize velocity stream plots without manually instantiating the class.
- Parameters:
adata (AnnData) – The AnnData object containing the data to plot.
ax (Optional[Union[plt.Axes, List[plt.Axes]]], optional) – Matplotlib axes object or list of axes objects on which to draw the plots. If None, a new figure and axes are created. Default:
None.c (str, optional) – Color for the scatter plot points. Can be a column name from adata.obs if coloring by a categorical variable. Default:
"dodgerblue".cmap (Optional[Union[Dict, List, Tuple, str]], optional) – Colormap for the scatter plot points if c is a categorical variable. Default:
"plasma_r".group_zorder (Optional[Dict], optional) – Z-order for groups in the scatter plot, allowing certain groups to be plotted on top of others. Default:
None.linewidth (float, optional) – Line width for the streamlines. Default:
0.5.stream_density (float, optional) – Density of the streamlines. Higher values create more densely packed streamlines. Default:
2.5.add_margin (float, optional) – Additional margin added around the plotted data, specified as a fraction of the data range. Default:
0.1.arrowsize (float, optional) – Size of the arrows in the stream plot. Default:
1.arrowstyle (str, optional) – Style of the arrows in the stream plot. Default:
"-|>".maxlength (float, optional) – Maximum length of the arrows in the stream plot. Default:
4.integration_direction (str, optional) – Direction of integration for the streamlines, can be “forward”, “backward”, or “both”. Default:
"both".scatter_zorder (int, optional) – Z-order for scatter plot points, determining their layering. Default:
101.stream_zorder (int, optional) – Z-order for the streamlines, determining their layering. Default:
201.density (float, optional) – Default:
1.smooth (float, optional) – Default:
0.5.n_neighbors (Optional[int], optional) – Default:
None.min_mass (float, optional) – Default:
1.autoscale (bool, optional) – Default:
True.stream_adjust (bool, optional) – Default:
True.cutoff_percentile (float, optional)
velocity_key (str, optional)
self_transitions (bool, optional)
use_negative_cosines (bool, optional)
T_scale (float, optional)
disable_scatter (bool, optional) – If True, disables the scatter plot overlay on the stream plot. Default:
False.disable_cbar (bool, optional) – If True, disables the color bar for the scatter plot. Useful when c is numeric. Default:
False.stream_kwargs (Optional[Dict[str, Any]], optional)
scatter_kwargs (Optional[Dict[str, Any]], optional)
cbar_kwargs (Optional[Dict], optional)
mpl_kwargs (Optional[Dict[str, Any]], optional) – Additional keyword arguments for customizing the stream plot, scatter plot, color bar, and matplotlib figure, respectively.
return_axes (bool, optional) – If True, returns the matplotlib axes with the generated plots. Default:
False.save (bool, optional) – If True, saves the generated plot to SVG and PNG formats. Default:
False.png_dpi (Optional[float], optional) – DPI settings for saving PNG images. Default:
500.svg_dpi (Optional[float], optional) – DPI settings for saving SVG images. Default:
250.
- Returns:
A list of matplotlib axes with the generated plots, if
return_axes == True. Otherwise, returnsNone.- Return type:
Optional[Union[List[plt.Axes], None]]
sdq.pl.temporal_expression
- scdiffeq.plotting._temporal_expression.temporal_expression(adata_sim: AnnData, gene: str, groupby: str = 'final_state', groups: List[str] | None = None, use_key: str = 'X_gene_inv', time_key: str = 't', gene_ids_key: str = 'gene_ids', show_std: bool = True, std_alpha: float = 0.2, ax: Axes | None = None, figsize: tuple = (3, 2.5), cmap: Dict[str, str] | None = None, linewidth: float = 2.0, x_label: str = 't(d)', y_label: str = 'Log-norm. expression', title: str | None = None, show_legend: bool = True, legend_loc: str | tuple = 'best', grid: bool = True, grid_alpha: float = 0.3, save: bool = False, savename: str | None = None, save_format: str = 'svg', dpi: int = 300) Axes[source]
Plot gene expression over simulated time, grouped by fate.
Computes mean and standard deviation at each time step and plots as line (mean) with shaded fill-between region (±1 std).
- Parameters:
adata_sim (AnnData) – Simulated data from
sdq.tl.simulate(), with gene expression stored in obsm after callingsdq.tl.invert_scaled_gex().gene (str) – Gene name to plot.
groupby (str, default="final_state") – Column in
adata_sim.obsfor grouping trajectories (e.g., cell fate).groups (List[str], optional) – Specific groups to plot. If None, plots all groups. Use this to exclude certain groups (e.g.,
groups=["Mon.", "Neu."]to only plot those two fates).use_key (str, default="X_gene_inv") – Key in
adata_sim.obsmcontaining the gene expression matrix.time_key (str, default="t") – Column in
adata_sim.obscontaining time values.gene_ids_key (str, default="gene_ids") – Key in
adata_sim.unscontaining gene names array.show_std (bool, default=True) – Whether to show standard deviation as shaded fill-between region.
std_alpha (float, default=0.2) – Transparency of the standard deviation shading.
ax (plt.Axes, optional) – Matplotlib axes to plot on. If None, creates new figure.
figsize (tuple, default=(3, 2.5)) – Figure size (width, height) in inches if creating new figure.
cmap (Dict[str, str], optional) – Mapping from group names to colors. If None, uses default colormap.
linewidth (float, default=2.0) – Width of the mean line.
x_label (str, default="t(d)") – Label for x-axis.
y_label (str, default="Log-norm. expression") – Label for y-axis.
title (str, optional) – Plot title. If None, uses gene name in italic.
show_legend (bool, default=True) – Whether to show legend.
legend_loc (str or tuple, default="best") – Legend location.
grid (bool, default=True) – Whether to show grid.
grid_alpha (float, default=0.3) – Transparency of grid lines.
save (bool, default=False) – Whether to save the figure.
savename (str, optional) – Filename for saving. If None, auto-generates from gene name.
save_format (str, default="svg") – Format for saving figure.
dpi (int, default=300) – Resolution for saving figure.
- Returns:
The matplotlib axes object.
- Return type:
plt.Axes
Examples
>>> import scdiffeq as sdq >>> adata_sim = sdq.tl.simulate(adata, diffeq=model, idx=idx) >>> sdq.tl.invert_scaled_gex(adata_sim, ...) >>> sdq.tl.annotate_cell_fate(adata_sim, ...) >>> sdq.pl.temporal_expression( ... adata_sim, ... gene="Spi1", ... groupby="final_state", ... cmap={"Mon.": "orange", "Neu.": "#4a7298"} ... )
sdq.pl.simulation_umap
- scdiffeq.plotting._simulation_umap.simulation_umap(adata_sim: AnnData, color: str = 't', use_key: str = 'X_umap', gene_key: str = 'X_gene_inv', gene_ids_key: str = 'gene_ids', ax: Axes | None = None, figsize: tuple = (4, 4), cmap: str | Colormap = 'viridis', categorical_cmap: Dict[str, str] | None = None, s: float = 1.0, alpha: float = 0.8, title: str | None = None, show_colorbar: bool = True, colorbar_label: str | None = None, show_legend: bool = True, legend_loc: str = 'best', save: bool = False, savename: str | None = None, save_format: str = 'svg', dpi: int = 300, **kwargs) Axes[source]
Plot UMAP embedding of simulated data, colored by obs attribute or gene expression.
- Parameters:
adata_sim (AnnData) – Simulated data from
sdq.tl.simulate(), with UMAP coordinates in obsm and optionally gene expression in obsm after callingsdq.tl.invert_scaled_gex().color (str, default="t") – What to color points by. Can be: - Column name in
adata_sim.obs(e.g., “t”, “fate”, “sim_i”) - Gene name (will look up in gene_ids_key and extract from gene_key)use_key (str, default="X_umap") – Key in
adata_sim.obsmcontaining UMAP coordinates.gene_key (str, default="X_gene_inv") – Key in
adata_sim.obsmcontaining gene expression matrix.gene_ids_key (str, default="gene_ids") – Key in
adata_sim.unscontaining gene names.ax (plt.Axes, optional) – Matplotlib axes to plot on. If None, creates new figure.
figsize (tuple, default=(4, 4)) – Figure size (width, height) in inches if creating new figure.
cmap (str or Colormap, default="viridis") – Colormap for continuous values.
categorical_cmap (Dict[str, str], optional) – Mapping from category names to colors for categorical data.
s (float, default=1.0) – Point size.
alpha (float, default=0.8) – Point transparency.
title (str, optional) – Plot title. If None, uses the color parameter.
show_colorbar (bool, default=True) – Whether to show colorbar for continuous values.
colorbar_label (str, optional) – Label for colorbar. If None, uses the color parameter.
show_legend (bool, default=True) – Whether to show legend for categorical values.
legend_loc (str, default="best") – Legend location.
save (bool, default=False) – Whether to save the figure.
savename (str, optional) – Filename for saving. If None, auto-generates from color parameter.
save_format (str, default="svg") – Format for saving figure.
dpi (int, default=300) – Resolution for saving figure.
**kwargs – Additional keyword arguments passed to
ax.scatter()(e.g.,zorder,edgecolors,linewidths).
- Returns:
The matplotlib axes object.
- Return type:
plt.Axes
Examples
>>> import scdiffeq as sdq >>> # Color by time >>> sdq.pl.simulation_umap(adata_sim, color="t") >>> # Color by fate >>> sdq.pl.simulation_umap(adata_sim, color="fate", categorical_cmap={"Mon.": "orange", "Neu.": "blue"}) >>> # Color by gene expression >>> sdq.pl.simulation_umap(adata_sim, color="Myc")
sdq.pl.simulation_trajectory_gif
- scdiffeq.plotting._simulation_trajectory_gif.simulation_trajectory_gif(adata_sim: AnnData, savename: str = 'simulation_trajectory.gif', color: str = 't', use_key: str = 'X_umap', time_key: str = 't', gene_key: str = 'X_gene_inv', gene_ids_key: str = 'gene_ids', figsize: tuple = (6, 6), cmap: str | Colormap = 'plasma_r', s: float = 10.0, alpha: float = 0.8, background_fn: Callable | None = None, background_groupby: str | None = None, background_cmap: Dict[str, str] | None = None, background_s: float = 100.0, background_inner_s: float = 65.0, umap_labels: List[Dict] | None = None, show_time_label: bool = True, time_label_fmt: str = 't = {:.1f}d', time_label_loc: tuple = (0.05, 0.95), time_label_fontsize: int = 12, title: str | None = None, fps: int = 10, duration: float | None = None, hold_frames: int = 10, fade_frames: int = 8, leading_edge_scale: float = 2.0, trail_alpha: float = 0.5, show_progenitor: bool = True, progenitor_frames: int = 8, progenitor_label: str = 'Progenitor', progenitor_s: float = 80.0, progenitor_color: str = 'dodgerblue', dpi: int = 100, return_fig: bool = False, **kwargs) str | tuple[source]
Create a GIF of simulation trajectories growing over UMAP space.
- Parameters:
adata_sim (AnnData) – Simulated data from
sdq.tl.simulate(), with UMAP coordinates in obsm.savename (str, default="simulation_trajectory.gif") – Output filename for the GIF.
color (str, default="t") – What to color points by. Can be column in obs or gene name.
use_key (str, default="X_umap") – Key in
adata_sim.obsmcontaining UMAP coordinates.time_key (str, default="t") – Column in
adata_sim.obscontaining time values.gene_key (str, default="X_gene_inv") – Key in
adata_sim.obsmcontaining gene expression matrix.gene_ids_key (str, default="gene_ids") – Key in
adata_sim.unscontaining gene names.figsize (tuple, default=(6, 6)) – Figure size (width, height) in inches.
cmap (str or Colormap, default="plasma_r") – Colormap for continuous values.
s (float, default=10.0) – Point size for simulation points.
alpha (float, default=0.8) – Point transparency.
background_fn (Callable, optional) – Custom function to plot background. Should accept (adata_sim, ax). If None, uses default background (or fate-colored if background_groupby set).
background_groupby (str, optional) – Column in obs to group background cells by (e.g., “final_state”). When set, background cells are colored by group using background_cmap.
background_cmap (Dict[str, str], optional) – Mapping from group names to colors for background. Required if background_groupby is set. Example: {“Mon.”: “orange”, “Neu.”: “#4a7298”}
background_s (float, default=100.0) – Point size for background outer points.
background_inner_s (float, default=65.0) – Point size for background inner points.
umap_labels (List[Dict], optional) – List of label dictionaries to draw on the UMAP. Each dict should have keys “text”, “x”, “y”, and optionally any matplotlib text kwargs like “color”, “fontsize”, “weight”, “ha”, “va”. Example: [{“text”: “Monocyte”, “x”: 10.5, “y”: 10, “color”: “#F08700”, “weight”: “bold”}]
show_time_label (bool, default=True) – Whether to show time label on each frame.
time_label_fmt (str, default="t = {:.1f}d") – Format string for time label.
time_label_loc (tuple, default=(0.05, 0.95)) – Location of time label in axes coordinates.
time_label_fontsize (int, default=12) – Font size for time label.
title (str, optional) – Plot title.
fps (int, default=10) – Frames per second for the GIF.
duration (float, optional) – Total duration in seconds. If provided, overrides fps.
hold_frames (int, default=10) – Number of frames to hold at the end before fading.
fade_frames (int, default=8) – Number of frames for the fade-out transition.
leading_edge_scale (float, default=2.0) – Size multiplier for leading edge points (current time step).
trail_alpha (float, default=0.5) – Alpha multiplier for trail points (older time steps), relative to base alpha.
show_progenitor (bool, default=True) – Whether to show progenitor intro frames at the start.
progenitor_frames (int, default=8) – Number of frames to hold on the progenitor before starting animation.
progenitor_label (str, default="Progenitor") – Label text for the progenitor annotation.
progenitor_s (float, default=80.0) – Point size for the progenitor marker.
progenitor_color (str, default="dodgerblue") – Color for the progenitor marker and annotation.
dpi (int, default=100) – Resolution for each frame.
return_fig (bool, default=False) – If True, also returns the final frame’s (fig, ax) tuple.
**kwargs – Additional keyword arguments passed to scatter.
- Returns:
Path to the saved GIF file. If return_fig=True, returns (savename, fig, ax) tuple with the final frame.
- Return type:
Examples
>>> import scdiffeq as sdq >>> # Basic usage >>> sdq.pl.simulation_trajectory_gif(adata_sim, savename="my_sim.gif") >>> # With custom background >>> def my_background(adata_sim, ax): ... xu = adata_sim.obsm["X_umap"] ... ax.scatter(xu[:, 0], xu[:, 1], c="lightgray", s=50) >>> sdq.pl.simulation_trajectory_gif(adata_sim, background_fn=my_background)
sdq.pl.simulation_expression_gif
- scdiffeq.plotting._simulation_expression_gif.simulation_expression_gif(adata_sim: AnnData, gene: str, savename: str = 'simulation_expression.gif', groupby: str = 'final_state', groups: List[str] | None = None, color: str = 't', use_key: str = 'X_umap', time_key: str = 't', gene_key: str = 'X_gene_inv', gene_ids_key: str = 'gene_ids', figsize: tuple = (12, 6), expr_width_scale: float = 0.8, expr_height_scale: float = 0.8, umap_cmap: str | Colormap = 'plasma_r', s: float = 10.0, alpha: float = 0.8, background_fn: Callable | None = None, background_groupby: str | None = None, background_cmap: Dict[str, str] | None = None, background_s: float = 100.0, background_inner_s: float = 65.0, umap_labels: List[Dict] | None = None, expr_cmap: Dict[str, str] | None = None, linewidth: float = 2.0, show_std: bool = True, std_alpha: float = 0.2, x_label: str = 't(d)', y_label: str = 'Log-norm. expression', show_time_label: bool = True, time_label_fmt: str = 't = {:.1f}d', time_label_loc: tuple = (0.05, 0.95), time_label_fontsize: int = 12, umap_title: str | None = None, fps: int = 10, duration: float | None = None, hold_frames: int = 10, fade_frames: int = 8, leading_edge_scale: float = 2.0, trail_alpha: float = 0.5, show_progenitor: bool = True, progenitor_frames: int = 8, progenitor_label: str = 'Progenitor', progenitor_s: float = 80.0, progenitor_color: str = 'dodgerblue', dpi: int = 100, return_fig: bool = False, **kwargs) str | tuple[source]
Create a dual-panel GIF with synchronized UMAP trajectory and gene expression.
Left panel shows the simulation trajectory growing over UMAP space. Right panel shows temporal gene expression (mean ± std) growing over time.
- Parameters:
adata_sim (AnnData) – Simulated data from
sdq.tl.simulate(), with UMAP coordinates in obsm and gene expression aftersdq.tl.invert_scaled_gex().gene (str) – Gene name to plot in the expression panel.
savename (str, default="simulation_expression.gif") – Output filename for the GIF.
groupby (str, default="final_state") – Column in
adata_sim.obsfor grouping trajectories in expression panel.groups (List[str], optional) – Specific groups to plot. If None, plots all groups.
color (str, default="t") – What to color UMAP points by. Can be column in obs or gene name.
use_key (str, default="X_umap") – Key in
adata_sim.obsmcontaining UMAP coordinates.time_key (str, default="t") – Column in
adata_sim.obscontaining time values.gene_key (str, default="X_gene_inv") – Key in
adata_sim.obsmcontaining gene expression matrix.gene_ids_key (str, default="gene_ids") – Key in
adata_sim.unscontaining gene names.figsize (tuple, default=(12, 6)) – Figure size (width, height) in inches for the dual-panel figure.
expr_width_scale (float, default=0.8) – Width of expression panel relative to UMAP panel. 0.8 means expression panel is 80% as wide as UMAP panel.
expr_height_scale (float, default=0.8) – Height scaling for expression panel. Uses GridSpec height_ratios to make expression panel shorter. 0.8 means expression panel is 80% as tall, with remaining space as padding.
umap_cmap (str or Colormap, default="plasma_r") – Colormap for UMAP continuous values.
s (float, default=10.0) – Point size for simulation points on UMAP.
alpha (float, default=0.8) – Point transparency on UMAP.
background_fn (Callable, optional) – Custom function to plot UMAP background. Should accept (adata_sim, ax).
background_groupby (str, optional) – Column in obs to group background cells by (e.g., “final_state”). When set, background cells are colored by group using background_cmap.
background_cmap (Dict[str, str], optional) – Mapping from group names to colors for background. Example: {“Mon.”: “orange”, “Neu.”: “#4a7298”}
background_s (float, default=100.0) – Point size for background outer points.
background_inner_s (float, default=65.0) – Point size for background inner points.
umap_labels (List[Dict], optional) – List of label dictionaries to draw on the UMAP panel. Each dict should have keys “text”, “x”, “y”, and optionally any matplotlib text kwargs like “color”, “fontsize”, “weight”, “ha”, “va”. Example: [{“text”: “Monocyte”, “x”: 10.5, “y”: 10, “color”: “#F08700”, “weight”: “bold”}]
expr_cmap (Dict[str, str], optional) – Mapping from group names to colors for expression panel.
linewidth (float, default=2.0) – Width of mean lines in expression panel.
show_std (bool, default=True) – Whether to show standard deviation shading in expression panel.
std_alpha (float, default=0.2) – Transparency of std shading.
x_label (str, default="t(d)") – X-axis label for expression panel.
y_label (str, default="Log-norm. expression") – Y-axis label for expression panel.
show_time_label (bool, default=True) – Whether to show time label on UMAP panel.
time_label_fmt (str, default="t = {:.1f}d") – Format string for time label.
time_label_loc (tuple, default=(0.05, 0.95)) – Location of time label in axes coordinates.
time_label_fontsize (int, default=12) – Font size for time label.
umap_title (str, optional) – Title for UMAP panel.
fps (int, default=10) – Frames per second for the GIF.
duration (float, optional) – Total duration in seconds. If provided, overrides fps.
hold_frames (int, default=10) – Number of frames to hold at the end before fading.
fade_frames (int, default=8) – Number of frames for the fade-out transition.
leading_edge_scale (float, default=2.0) – Size multiplier for leading edge points on UMAP.
trail_alpha (float, default=0.5) – Alpha multiplier for trail points on UMAP.
show_progenitor (bool, default=True) – Whether to show progenitor intro frames at the start.
progenitor_frames (int, default=8) – Number of frames to hold on the progenitor before starting animation.
progenitor_label (str, default="Progenitor") – Label text for the progenitor annotation.
progenitor_s (float, default=80.0) – Point size for the progenitor marker.
progenitor_color (str, default="dodgerblue") – Color for the progenitor marker and annotation.
dpi (int, default=100) – Resolution for each frame.
return_fig (bool, default=False) – If True, also returns the final frame’s (fig, ax_umap, ax_expr) tuple.
**kwargs – Additional keyword arguments passed to UMAP scatter.
- Returns:
Path to the saved GIF file. If return_fig=True, returns (savename, fig, ax_umap, ax_expr) tuple with the final frame.
- Return type:
Examples
>>> import scdiffeq as sdq >>> sdq.pl.simulation_expression_gif( ... adata_sim, ... gene="Spi1", ... groupby="final_state", ... expr_cmap={"Mon.": "orange", "Neu.": "#4a7298"} ... )