Plotting

class palantir.plot.FigureGrid(n: int, max_cols=3, scale=3)View on GitHub

Bases: object

Generates a grid of axes for plotting axes can be iterated over or selected by number. e.g.: >>> # iterate over axes and plot some nonsense >>> fig = FigureGrid(4, max_cols=2) >>> for i, ax in enumerate(fig): >>> plt.plot(np.arange(10) * i) >>> # select axis using indexing >>> ax3 = fig[3] >>> ax3.set_title(“I’m axis 3”)

palantir.plot.cell_types(tsne, clusters, cluster_colors=None, n_cols=5)View on GitHub

Plot cell clusters on the tSNE map :param tsne: tSNE map :param clusters: Results of the determine_cell_clusters function

palantir.plot.check_colornorm(vmin: float | None = None, vmax: float | None = None, vcenter: float | None = None, norm: Normalize | None = None) NormalizeView on GitHub

Checks and returns a matplotlib Normalize object for color mapping.

palantir.plot.density_2d(x, y)View on GitHub

return x and y and their density z, sorted by their density (smallest to largest) :param x: :param y: :return:

palantir.plot.gene_score_histogram(ad: AnnData, score_key: str, genes: List[str] | None = None, bins: int = 100, quantile: float | None = 0.95, extra_offset_fraction: float = 0.1, anno_min_diff_fraction: float = 0.05) FigureView on GitHub

Draw a histogram of gene scores with percentile line and annotations for specific genes.

Parameters:
  • ad (AnnData) – Annotated data matrix.

  • score_key (str) – The key in ad.var data frame for the gene score.

  • genes (Optional[List[str]], default=None) – List of genes to be annotated. If None, no genes are annotated.

  • bins (int, default=100) – The number of bins for the histogram.

  • quantile (Optional[float], default=0.95) – Quantile line to draw on the histogram. If None, no line is drawn.

  • extra_offset_fraction (float, default=0.1) – Fraction of max height to use as extra offset for annotation.

  • anno_min_diff_fraction (float, default=0.05) – Fraction of the range of the scores to be used as minimum difference for annotation.

Returns:

fig – Figure object with the histogram.

Return type:

matplotlib Figure

Raises:

ValueError – If input parameters are not as expected.

palantir.plot.get_fig(fig=None, ax=None)View on GitHub

fills in any missing axis or figure with the currently active one :param ax: matplotlib Axis object :param fig: matplotlib Figure object

palantir.plot.highlight_cells_on_umap(data: AnnData | DataFrame, cells: List[str] | Dict[str, str] | Series | Index | ndarray | str, annotation_offset: float = 0.03, s: float = 1, s_highlighted: float = 10, fig: Figure | None = None, ax: Axes | None = None, embedding_basis: str = 'X_umap', figsize: Tuple[float, float] = (6, 6)) Tuple[Figure, Axes]View on GitHub

Highlight and annotate specific cells on a UMAP plot.

Parameters:
  • data (Union[AnnData, pd.DataFrame]) – Either a Scanpy AnnData object or a DataFrame of UMAP coordinates.

  • cells (Union[List[str], Dict[str, str], pd.Series, pd.Index, np.ndarray, str]) –

    Cells to highlight on the UMAP. Can be provided as:
    • a list, dict, or pd.Series: used as cell names (values in dict/Series used as annotations).

    • a pd.Index: cell identifiers matching those in the data’s index will be highlighted.

    • a boolean array-like: used as a mask to select cells from the data’s index.

    • a string: used to retrieve a boolean mask from the AnnData’s .obs attribute.

  • annotation_offset (float, optional) – Offset for the annotations in proportion to the data range. Default is 0.03.

  • s (float, optional) – Size of the points in the scatter plot. Default is 1.

  • s_highlighted (float, optional) – Size of the points in the highlighted cells. Default is 10.

  • fig (Optional[plt.Figure], optional) – Matplotlib Figure object. If None, a new figure is created. Default is None.

  • ax (Optional[plt.Axes], optional) – Matplotlib Axes object. If None, a new Axes object is created. Default is None.

  • embedding_basis (str, optional) – The key to retrieve UMAP results from the AnnData object. Default is ‘X_umap’.

  • figsize (Tuple[float, float], optional) – Size of the figure (width, height) in inches. Default is (6, 6).

Returns:

  • fig (plt.Figure) – A matplotlib Figure object containing the UMAP plot.

  • ax (plt.Axes) – The corresponding Axes object.

Raises:
  • KeyError – If ‘embedding_basis’ is not found in ‘data.obsm’.

  • TypeError – If ‘cells’ is neither list, dict nor pd.Series.

palantir.plot.plot_branch(ad: AnnData, branch_name: str, position: str, color: str = None, masks_key: str = 'branch_masks', ax: Axes | None = None, pseudo_time_key: str = 'palantir_pseudotime', na_color: str = 'lightgray', color_layer: str | None = None, position_layer: str | None = None, legend_fontsize: int | float | Literal['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'] | None = None, legend_fontweight: int | Literal['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black'] = 'bold', legend_fontoutline: int | None = None, legend_anchor: Tuple[float, float] = (1.1, 0.5), color_bar_bounds: list = [1.1, 0.3, 0.02, 0.4], cmap: Colormap | str | None = None, palette: str | Sequence[str] | Cycler | None = None, vmax: str | float | Callable[[...], Any] | Sequence[str | float | Callable[[...], Any]] | None = None, vmin: str | float | Callable[[...], Any] | Sequence[str | float | Callable[[...], Any]] | None = None, vcenter: str | float | Callable[[...], Any] | Sequence[str | float | Callable[[...], Any]] | None = None, norm: Normalize | Sequence[Normalize] | None = None, nticks: int = 3, figsize: Tuple[float, float] = (12, 4), **kwargs)View on GitHub

This function visualizes a scatter plot of cells over pseudotime. The y-position indicates either a gene expression or any column from .obs or use a different position_layer, like “MAGIC_imputed_data”. The color follows similar rules and behaves like the color parameter in scanpy.pl.embedding, but only accepts a single value instead of a list.

Parameters:
  • ad (AnnData) – Annotated data matrix of shape n_obs x n_vars. Rows correspond to cells and columns to genes.

  • branch_name (str) – Specifies the branch to plot the trend for.

  • position (str) – Similar to color but used for y-position.

  • color (str, optional) – Defines the color to be used for the plot, similar to the color in scanpy.pl.embedding. If not provided, the default is None.

  • masks_key (str, optional) – Key for accessing the branch cell selection masks from obsm of the AnnData object. Default is ‘branch_masks’.

  • ax (Axes, optional) – A matplotlib axes object.

  • pseudo_time_key (str, optional) – Specifies the pseudotime key to be used for the plot. The default is “palantir_pseudotime”.

  • na_color (str, optional) – The color to be used for ‘NA’ values. Default is “lightgray”.

  • color_layer (str, optional) – Specifies the data layer to use for color in the plot. If not provided, the .X layer is used.

  • position_layer (str, optional) – Specifies the data layer to use for y-position in the plot. If not provided, the .X layer is used.

  • legend_fontsize (Union[int, float, _FontSize, None], optional) – Specifies the font size for the legend. Default is None.

  • legend_fontweight (Union[int, _FontWeight], optional) – Specifies the font weight for the legend. Default is ‘bold’.

  • legend_fontoutline (int, optional) – Specifies the font outline for the legend. Default is None.

  • legend_anchor (Tuple[float, float] = (1.1, 0.5),) – Defines the position of the legend. The argument will be passed to the bbox_to_anchor parameter of ax.legend() method. The default is (1.1, 0.5).

  • color_bar_bounds (list, optional) – Specifies the bounds for the color bar. Defaults to [1, 0.4, 0.01, 0.2].

  • cmap (Union[Colormap, str, None]) – A colormap instance or registered colormap name to color the scatter plot.

  • palette (Union[str, Sequence[str], Cycler, None], optional) – Colors to use for plotting categorical annotation groups. The palette can be a valid matplotlib.colors.ListedColormap name (‘viridis’, ‘Set2’, etc), a cycler.Cycler object, or a sequence of matplotlib colors like [‘red’, ‘blue’, ‘green’].

  • vmax (float or array-like or None) – Defines the lower limit of the color scale with values smaller than vmin sharing the same color. It can be a number, percentile string (‘pN’), function returning a desired value from the plot values, or None for automatic selection. For multiple plots, a list of vmin can be specified.

  • vmin (float or array-like or None) – Sets the upper limit of the color scale, with the same format and behavior as vmin.

  • vcenter (float or array-like or None) – Sets the center of the color scale, useful for diverging colormaps. It follows the same format and rules as vmin and vmax. Example: sc.pl.umap(adata, color=’TREM2’, vcenter=’p50’, cmap=’RdBu_r’).

  • norm (matplotlib.colors.Normalize or None) – The normalizing object which scales data, typically into the interval [0, 1]. If provided, vmax, vmin, and vcenter are ignored.

  • nticks (int, optional) – The number of ticks to be displayed on both the x and y axes. The matplotlib’s Axes.locator_params method is used for setting this property. Default is 3.

  • figsize (Tuple[float, float], optional) – Width and height of each subplot in inches. Default is (12, 4).

Returns:

fig, ax

Return type:

figure and axis elements of the plot.

Raises:
  • TypeError – If input parameters are not of the expected type.

  • ValueError – If input parameters do not have the expected values.

palantir.plot.plot_branch_selection(ad: AnnData, pseudo_time_key: str = 'palantir_pseudotime', fate_prob_key: str = 'palantir_fate_probabilities', masks_key: str = 'branch_masks', fates: List[str] | str | None = None, embedding_basis: str = 'X_umap', figsize: Tuple[float, float] = (15, 5), **kwargs)View on GitHub

Plot cells along specific fates of pseudotime ordering and the UMAP embedding.

Parameters:
  • ad (AnnData) – Annotated data matrix. The pseudotime and fate probabilities should be stored under the keys provided.

  • pseudo_time_key (str, optional) – Key to access the pseudotime from obs of the AnnData object. Default is ‘palantir_pseudotime’.

  • fate_prob_key (str, optional) – Key to access the fate probabilities from obsm of the AnnData object. Default is ‘palantir_fate_probabilities’.

  • masks_key (str, optional) – Key to access the branch cell selection masks from obsm of the AnnData object. Default is ‘branch_masks’.

  • fates (Union[List[str], str]) – The fates to be plotted. If not specified, all fates will be plotted.

  • embedding_basis (str, optional) – Key to access the UMAP embedding from obsm of the AnnData object. Default is ‘X_umap’.

  • figsize (Tuple[float, float], optional) – Width and height of each subplot in inches. The total height of the figure is determined by multiplying the height by the number of fates. Default is (15, 5).

  • **kwargs – Additional arguments passed to matplotlib.pyplot.scatter.

Returns:

A matplotlib Figure object representing the plot of the branch selections.

Return type:

matplotlib.pyplot.Figure

palantir.plot.plot_diffusion_components(data: AnnData | DataFrame, dm_res: DataFrame | str | None = 'DM_EigenVectors', embedding_basis: str = 'X_umap', **kwargs) Tuple[Figure, Axes]View on GitHub

Visualize diffusion components on tSNE or UMAP plots.

Parameters:
  • data (Union[AnnData, pd.DataFrame]) – An AnnData object from Scanpy or a DataFrame that contains tSNE or UMAP results.

  • dm_res (Optional[Union[pd.DataFrame, str]], optional) – A DataFrame that contains the diffusion map results or a string key to access diffusion map results from the obsm of the AnnData object. Default is ‘DM_Eigenvectors’.

  • embedding_basis (str, optional) – Key to access UMAP results from the obsm of the AnnData object. Defaults to ‘X_umap’.

  • kwargs (dict, optional) – Additional keyword arguments to pass to the scatter plot function.

Returns:

A tuple containing the matplotlib Figure and Axes objects representing the diffusion component plot.

Return type:

Tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes]

Raises:

KeyError – If embedding_basis or dm_res is not found in .obsm when data is an AnnData object.

palantir.plot.plot_gene_expression(data: DataFrame, tsne: DataFrame, genes: List[str], plot_scale: bool = False, n_cols: int = 5, percentile: int = 0, **kwargs) FigureView on GitHub

Plot gene expression overlaid on tSNE maps.

Parameters:
  • data (pd.DataFrame) – A DataFrame where each column represents a gene and each row a cell.

  • tsne (pd.DataFrame) – A DataFrame containing tSNE coordinates for each cell.

  • genes (List[str]) – List of gene symbols to plot on tSNE.

  • plot_scale (bool, optional) – If True, include a color scale bar in the plot. Defaults to False.

  • n_cols (int, optional) – Number of columns in the subplot grid. Defaults to 5.

  • percentile (int, optional) – Percentile to cut off extreme values in gene expression for plotting. Defaults to 0, meaning no cutoff.

  • kwargs (dict, optional) – Additional keyword arguments to pass to the scatter plot function.

Returns:

A matplotlib Figure object representing the plot of the gene expression.

Return type:

matplotlib.pyplot.Figure

Raises:

ValueError – If none of the genes in the list are found in the data.

palantir.plot.plot_gene_trend_clusters(data: AnnData | DataFrame, branch_name: str = '', clusters: Series | str | None = None, gene_trend_key: str | None = 'gene_trends') FigureView on GitHub

Visualize gene trend clusters.

This function accepts either a Scanpy AnnData object or a DataFrame of gene expression trends, along with a Series of clusters or a key to clusters in AnnData object’s var. It creates a plot representing gene trend clusters.

Parameters:
  • data (Union[AnnData, pd.DataFrame]) – AnnData object or DataFrame of gene expression trends.

  • branch_name (str, optional) – Name of the branch for which to plot gene trends. It is added to the gene_trend_key when accessing gene trends from varm. Defaults to “”.

  • clusters (Union[pd.Series, str], optional) – Series of clusters indexed by gene names or string key to access clusters from the AnnData object’s var. If data is a DataFrame, clusters should be a Series. Default key is ‘gene_trend_key + “_” + branch_name + “_clusters”’.

  • gene_trend_key (str, optional) – Key to access gene trends in the AnnData object’s varm. Default is ‘gene_trends’.

Returns:

Matplotlib Figure object representing the plot of the gene trend clusters.

Return type:

matplotlib.pyplot.Figure

Raises:

KeyError – If gene_trend_key is None when data is an AnnData object.

palantir.plot.plot_gene_trend_heatmaps(data: AnnData | Dict, genes: List[str] | None = None, gene_trend_key: str = 'gene_trends', branch_names: str | List[str] = 'branch_masks', scaling: Literal['none', 'z-score', 'quantile', 'percent'] | None = 'z-score', basefigsize: Tuple[int, int] = (7, 0.7), cbkwargs: Dict = {}, **kwargs) FigureView on GitHub

Plot the gene trends on heatmaps: a heatmap is generated for each branch.

Parameters:
  • data (Union[AnnData, Dict]) – AnnData object or dictionary of gene trends.

  • genes (Optional[List[str]], optional) – List of genes to include in the plot. If None, all genes are included. Default is None.

  • gene_trend_key (str, optional) – Key to access gene trends in the AnnData object’s varm. Default is ‘gene_trends’.

  • branch_names (Union[str, List[str]], optional) – Key to access branch names from AnnData object or list of branch names. If a string is provided, it is assumed to be a key in AnnData.uns. Default is ‘branch_masks_columns’.

  • scaling (Optional[Literal["none", "z-score", "quantile", "percent"]], optional) – Scaling method to apply on the gene trends. Options are: - “none” : no scaling is applied. - “z-score” : standardizes the data to have 0 mean and 1 variance. - “quantile” : scales the data to have values between 0 and 1. - “percent” : scales the data to represent percentages of the max value in the row. Default is ‘z-score’.

  • basefigsize (Tuple[int, int], optional) – Base width and height in inches of the figure. The actual height of the figure is calculated based on the number of genes and branches. Default base size is (7, 0.7).

  • cbkwargs (dict) – Additional keyword arguments for matplotlib.pyplot.colorbar.

  • **kwargs (dict) – Additional keyword arguments for matplotlib.pyplot.matshow.

Returns:

fig – Matplotlib figure object of the plot.

Return type:

matplotlib.figure.Figure

Plot the gene trends for each gene across different panels.

Parameters:
  • data (Union[Dict, AnnData]) – An AnnData object or a dictionary that contains the gene trends.

  • genes (Optional[List[str]], optional) – A list of genes to plot. If not provided, all genes will be plotted. Default is None.

  • gene_trend_key (str, optional) – The key to access gene trends in the varm of the AnnData object. Default is ‘gene_trends’.

  • branch_names (Union[str, List[str]], optional) – Key to retrieve branch names from the AnnData object, or a list of branch names. If a string is provided, it will be treated as a key in either AnnData.uns or AnnData.obsm. For AnnData.obsm, the column names will be treated as branch names. If it cannot be found in AnnData.obsm and AnnData.uns then branch_names + “_columns” will be looked up in AnnData.uns. Default is ‘branch_masks’.

Returns:

fig – The matplotlib figure object containing the plot.

Return type:

matplotlib.figure.Figure

Raises:
  • KeyError – If ‘branch_names’ as a string is not found in either .uns or .obsm, or if ‘gene_trend_key + “_” + branch_name’ is not found in .varm.

  • ValueError – If ‘data’ is not an AnnData object and not a dictionary.

Plot the gene trends: each gene is plotted in a different panel :param: gene_trends: Results of the compute_marker_trends function

palantir.plot.plot_molecules_per_cell_and_gene(data, fig=None, ax=None)View on GitHub
palantir.plot.plot_palantir_results(data: AnnData | DataFrame, pr_res: PResults | None = None, embedding_basis: str = 'X_umap', pseudo_time_key: str = 'palantir_pseudotime', entropy_key: str = 'palantir_entropy', fate_prob_key: str = 'palantir_fate_probabilities', **kwargs)View on GitHub

Plot Palantir results on t-SNE or UMAP plots.

Parameters:
  • data (Union[AnnData, pd.DataFrame]) – Either a Scanpy AnnData object or a DataFrame of tSNE or UMAP results.

  • pr_res (Optional[PResults]) – Optional PResults object containing Palantir results. If None, results are expected to be found in the provided AnnData object.

  • embedding_basis (str, optional) – The key to retrieve UMAP results from the AnnData object. Defaults to ‘X_umap’.

  • pseudo_time_key (str, optional) – Key to access the pseudotime from obs of the AnnData object. Default is ‘palantir_pseudotime’.

  • entropy_key (str, optional) – Key to access the entropy from obs of the AnnData object. Default is ‘palantir_entropy’.

  • fate_prob_key (str, optional) – Key to access the fate probabilities from obsm of the AnnData object. Default is ‘palantir_fate_probabilities’.

  • **kwargs – Additional keyword arguments passed to ax.scatter.

Returns:

A matplotlib Figure object representing the plot of the Palantir results.

Return type:

matplotlib.pyplot.Figure

palantir.plot.plot_stats(ad: AnnData, x: str, y: str, color: str = None, ax: Axes | None = None, na_color: str = 'lightgray', color_layer: str | None = None, x_layer: str | None = None, y_layer: str | None = None, branch_name: str | None = None, masks_key: str = 'branch_masks', legend_fontsize: int | float | Literal['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'] | None = None, legend_fontweight: int | Literal['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black'] = 'bold', legend_fontoutline: int | None = None, legend_anchor: Tuple[float, float] = (1.1, 0.5), color_bar_bounds: list = [1.1, 0.3, 0.02, 0.4], cmap: Colormap | str | None = None, palette: str | Sequence[str] | Cycler | None = None, vmax: str | float | Callable[[...], Any] | Sequence[str | float | Callable[[...], Any]] | None = None, vmin: str | float | Callable[[...], Any] | Sequence[str | float | Callable[[...], Any]] | None = None, vcenter: str | float | Callable[[...], Any] | Sequence[str | float | Callable[[...], Any]] | None = None, norm: Normalize | Sequence[Normalize] | None = None, nticks: int = 3, figsize: Tuple[float, float] = (6, 6), **kwargs)View on GitHub

This function visualizes a scatter plot of cells over pseudotime. The y-position indicates either a gene expression or any column from .obs or use a different position_layer, like “MAGIC_imputed_data”. The color follows similar rules and behaves like the color parameter in scanpy.pl.embedding, but only accepts a single value instead of a list.

Parameters:
  • ad (AnnData) – Annotated data matrix of shape n_obs x n_vars. Rows correspond to cells and columns to genes.

  • x (str) – Similar to color but used for x-position.

  • y (str) – Similar to color but used for y-position.

  • color (str, optional) – Defines the color to be used for the plot, similar to the color in scanpy.pl.embedding. If not provided, the default is None.

  • ax (Axes, optional) – A matplotlib axes object.

  • na_color (str, optional) – The color to be used for ‘NA’ values. Default is “lightgray”.

  • color_layer (str, optional) – Specifies the data layer to use for color in the plot. If not provided, the .X layer is used.

  • x_layer (str, optional) – Specifies the data layer to use for x-position in the plot. If not provided, the .X layer is used.

  • y_layer (str, optional) – Specifies the data layer to use for y-position in the plot. If not provided, the .X layer is used.

  • branch_name (str, optional) – Specifies the branch to subset the plot to. The default is None.

  • masks_key (str, optional) – Key for accessing the branch cell selection masks from obsm of the AnnData object. Default is ‘branch_masks’.

  • legend_fontsize (Union[int, float, _FontSize, None], optional) – Specifies the font size for the legend. Default is None.

  • legend_fontweight (Union[int, _FontWeight], optional) – Specifies the font weight for the legend. Default is ‘bold’.

  • legend_fontoutline (int, optional) – Specifies the font outline for the legend. Default is None.

  • legend_anchor (Tuple[float, float] = (1.1, 0.5),) – Defines the position of the legend. The argument will be passed to the bbox_to_anchor parameter of ax.legend() method. The default is (1.1, 0.5).

  • color_bar_bounds (list, optional) – Specifies the bounds for the color bar. Defaults to [1, 0.4, 0.01, 0.2].

  • cmap (Union[Colormap, str, None]) – A colormap instance or registered colormap name to color the scatter plot.

  • palette (Union[str, Sequence[str], Cycler, None], optional) – Colors to use for plotting categorical annotation groups. The palette can be a valid matplotlib.colors.ListedColormap name (‘viridis’, ‘Set2’, etc), a cycler.Cycler object, or a sequence of matplotlib colors like [‘red’, ‘blue’, ‘green’].

  • vmax (float or array-like or None) – Defines the lower limit of the color scale with values smaller than vmin sharing the same color. It can be a number, percentile string (‘pN’), function returning a desired value from the plot values, or None for automatic selection. For multiple plots, a list of vmin can be specified.

  • vmin (float or array-like or None) – Sets the upper limit of the color scale, with the same format and behavior as vmin.

  • vcenter (float or array-like or None) – Sets the center of the color scale, useful for diverging colormaps. It follows the same format and rules as vmin and vmax. Example: sc.pl.umap(adata, color=’TREM2’, vcenter=’p50’, cmap=’RdBu_r’).

  • norm (matplotlib.colors.Normalize or None) – The normalizing object which scales data, typically into the interval [0, 1]. If provided, vmax, vmin, and vcenter are ignored.

  • nticks (int, optional) – The number of ticks to be displayed on both the x and y axes. The matplotlib’s Axes.locator_params method is used for setting this property. Default is 3.

  • figsize (Tuple[float, float], optional) – Width and height of each subplot in inches. Default is (12, 4).

Returns:

fig, ax

Return type:

figure and axis elements of the plot.

Raises:
  • TypeError – If input parameters are not of the expected type.

  • ValueError – If input parameters do not have the expected values.

palantir.plot.plot_terminal_state_probs(data: AnnData | DataFrame, cells: List[str], pr_res: PResults | None = None, fate_prob_key: str = 'palantir_fate_probabilities', **kwargs)View on GitHub

Function to plot barplot for probabilities for each cell in the list

Parameters:
  • data (Union[AnnData, pd.DataFrame]) – Either a Scanpy AnnData object or a DataFrame of fate probabilities.

  • cells (List[str]) – List of cell for which the barplots need to be plotted.

  • pr_res (Optional[PResults]) – Optional PResults object containing Palantir results. If None, results are expected to be found in the provided AnnData object.

  • fate_prob_key (str, optional) – Key to access the fate probabilities from obsm of the AnnData object. Default is ‘palantir_fate_probabilities’.

  • kwargs (dict, optional) – Additional keyword arguments to pass to the matplotlib.pyplot.bar function.

Returns:

A matplotlib Figure object representing the plot of the cell fate probabilities.

Return type:

matplotlib.pyplot.Figure

palantir.plot.plot_trajectories(ad, groups: List[str] | None = None, pseudo_time_key: str = 'palantir_pseudotime', masks_key: str = 'branch_masks', embedding_basis: str = 'X_umap', cell_color: str = 'palantir_pseudotime', palantir_fates_colors: List[str] | Dict[str, str] | None = None, smoothness: float = 1.0, pseudotime_interval: Tuple[float, float] | List[float] | ndarray | None = None, n_arrows: int = 5, arrowprops: dict | None = None, outline_arrowprops: dict | None = None, ax: Axes | None = None, scanpy_kwargs: dict | None = None, figsize: Tuple[float, float] = (5, 5), show_legend: bool = True, legend_kwargs: dict | None = None, **kwargs)View on GitHub

Plot trajectories for multiple branches on the UMAP embedding.

This function plots trajectories for either a selection or all branches. It colors the trajectories using a combination of predefined colors stored in ad.uns and/or user-specified palette. Any missing branch colors are generated such that duplicates are avoided.

Parameters:
  • ad (AnnData) – Annotated data matrix. Pseudotime and branch masks should be stored under given keys.

  • groups (list of str, optional) – List of branch names to plot. If None, all branches are used.

  • pseudo_time_key (str, optional) – Key in ad.obs for pseudotime values.

  • masks_key (str, optional) – Key in ad.obsm where branch masks are stored.

  • embedding_basis (str, optional) – Key in ad.obsm for the low-dimensional embedding (e.g. UMAP).

  • cell_color (str or None, optional) – How to color the cells. If “branch_selection”, non-selected cells are drawn with a deselected color. Otherwise, an external plotting function may be used.

  • palantir_fates_colors (dict or list, optional) – Mapping or ordered list of colors (for each branch). Missing colors are generated uniquely.

  • smoothness (float, optional) – Controls the smoothness of the trajectory. Higher values yield smoother curves.

  • pseudotime_interval (tuple, list, np.ndarray, optional) – Interval for pseudotime evaluation. If None, it is determined per branch.

  • n_arrows (int, optional) – Number of arrows to annotate the trajectory.

  • arrowprops (dict, optional) – Properties for the arrow style of the branch-specific (foreground) arrows.

  • outline_arrowprops (dict, optional) – Properties for the outline (background) arrows. Defaults to a thicker black arrow.

  • ax (matplotlib.axes.Axes, optional) – Matplotlib axes object to plot on. If None, a new figure is created.

  • scanpy_kwargs (dict, optional) – Extra keyword arguments for an external embedding plotting function.

  • figsize (tuple of float, optional) – Size of the figure (width, height).

  • show_legend (bool, optional) – Whether to display a legend for the branches. Default is True.

  • legend_kwargs (dict, optional) – Additional keyword arguments for customizing the legend appearance. Defaults to {“frameon”: False} if not provided.

  • **kwargs – Extra keyword arguments passed to the trajectory plotting (e.g., line style).

Returns:

The axis object containing the plot.

Return type:

matplotlib.axes.Axes

palantir.plot.plot_trajectory(ad: AnnData, branch: str, ax: Axes | None = None, pseudo_time_key: str = 'palantir_pseudotime', masks_key: str = 'branch_masks', embedding_basis: str = 'X_umap', cell_color: str = 'branch_selection', smoothness: float = 1.0, pseudotime_interval: Tuple[float, float] | List[float] | ndarray | None = None, n_arrows: int = 5, arrowprops: dict | None = {}, scanpy_kwargs: dict | None = {}, figsize: Tuple[float, float] = (5, 5), **kwargs)View on GitHub

Plot a trajectory on the UMAP embedding of single-cell data.

Parameters:
  • ad (AnnData) – Annotated data matrix. Pseudotime and fate probabilities should be stored under provided keys.

  • branch (str) – Branch/fate to plot the trajectory for.

  • ax (matplotlib.axes.Axes, optional) – Matplotlib axes object to plot on. If None, a new figure is created.

  • pseudo_time_key (str, optional) – Key for pseudotime data in ad.obs. Defaults to ‘palantir_pseudotime’.

  • masks_key (str, optional) – Key for branch cell selection masks in ad.obsm. Defaults to ‘branch_masks’.

  • embedding_basis (str, optional) – Key for UMAP embedding in ad.obsm. Defaults to ‘X_umap’.

  • cell_color (str or None, optional) – Coloring strategy for UMAP plot. ‘branch_selection’ highlights cells in the branch. If None, no coloring is applied. Defaults to ‘branch_selection’.

  • smoothness (float, optional) – Smoothness of fitted trajectory. Higher value means smoother. Defaults to 1.

  • pseudotime_interval (tuple, list, np.ndarray, optional) – Interval for pseudotime values. If None, it is automatically determined.

  • n_arrows (int, optional) – Number of arrows to plot. Defaults to 5.

  • arrowprops (dict, optional) – Properties for the arrowstyle. If None, defaults to black arrow with lw=1.

  • scanpy_kwargs (dict, optional) – Keyword arguments for the scanpy.pl.emebdding function to plot the cells.

  • figsize (Tuple[float, float], optional) – Size of the plot in inches, as (width, height). Defaults to (5, 5).

  • **kwargs – Extra keyword arguments are passed to the plot function for trajectory lines.

Returns:

The axes object with the trajectory plot.

Return type:

matplotlib.axes.Axes

palantir.plot.plot_trend(ad: AnnData, branch_name: str, gene: str, color: str = None, masks_key: str = 'branch_masks', gene_trend_key: str = 'gene_trends', ax: Axes | None = None, pseudo_time_key: str = 'palantir_pseudotime', na_color: str = 'lightgray', position: str = None, color_layer: str | None = None, position_layer: str | None = None, legend_fontsize: int | float | Literal['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'] | None = None, legend_fontweight: int | Literal['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black'] = 'bold', legend_fontoutline: int | None = None, legend_anchor: Tuple[float, float] = (1.1, 0.5), color_bar_bounds: list = [1.1, 0.3, 0.02, 0.4], cmap: Colormap | str | None = None, palette: str | Sequence[str] | Cycler | None = None, vmax: str | float | Callable[[...], Any] | Sequence[str | float | Callable[[...], Any]] | None = None, vmin: str | float | Callable[[...], Any] | Sequence[str | float | Callable[[...], Any]] | None = None, vcenter: str | float | Callable[[...], Any] | Sequence[str | float | Callable[[...], Any]] | None = None, norm: Normalize | Sequence[Normalize] | None = None, nticks: int = 3, figsize: Tuple[float, float] = (12, 4), **kwargs)View on GitHub

This function visualizes a trend graph for a specific gene’s expression over pseudotime. It plots the trend of a single gene for a chosen branch and additionally overlays a scatter plot of cells from the same branch. The y-position indicates the gene expression and can be configured to take any column from .obs or use a different layer, like “MAGIC_imputed_data”. The color follows similar rules and behaves like the color parameter in scanpy.pl.embedding, but only accepts a single value instead of a list.

Parameters:
  • ad (AnnData) – Annotated data matrix of shape n_obs x n_vars. Rows correspond to cells and columns to genes.

  • gene (str) – Specifies the gene to be plotted.

  • branch_name (str) – Specifies the branch to plot the trend for.

  • color (str, optional) – Defines the color to be used for the plot, similar to the color in scanpy.pl.embedding. If not provided, the default is None.

  • masks_key (str, optional) – Key for accessing the branch cell selection masks from obsm of the AnnData object. Set to None to disable the scatter plot. Default is ‘branch_masks’.

  • gene_trend_key (str, optional) – Key for accessing gene trends in the AnnData object’s varm. Default is ‘gene_trends’.

  • ax (Axes, optional) – A matplotlib axes object.

  • pseudo_time_key (str, optional) – Specifies the pseudotime key to be used for the plot. The default is “palantir_pseudotime”.

  • na_color (str, optional) – The color to be used for ‘NA’ values. Default is “lightgray”.

  • position (str, optional) – Similar to color but used for y-position. If None, the default is gene.

  • color_layer (str, optional) – Specifies the data layer to use for color in the plot. If not provided, the .X layer is used.

  • position_layer (str, optional) – Specifies the data layer to use for y-position in the plot. If not provided, the .X layer is used.

  • legend_fontsize (Union[int, float, _FontSize, None], optional) – Specifies the font size for the legend. Default is None.

  • legend_fontweight (Union[int, _FontWeight], optional) – Specifies the font weight for the legend. Default is ‘bold’.

  • legend_fontoutline (int, optional) – Specifies the font outline for the legend. Default is None.

  • legend_anchor (Tuple[float, float] = (1.1, 0.5),) – Defines the position of the legend. The argument will be passed to the bbox_to_anchor parameter of ax.legend() method. The default is (1.1, 0.5).

  • color_bar_bounds (list, optional) – Specifies the bounds for the color bar. Defaults to [1, 0.4, 0.01, 0.2].

  • cmap (Union[Colormap, str, None]) – A colormap instance or registered colormap name to color the scatter plot.

  • palette (Union[str, Sequence[str], Cycler, None], optional) – Colors to use for plotting categorical annotation groups. The palette can be a valid matplotlib.colors.ListedColormap name (‘viridis’, ‘Set2’, etc), a cycler.Cycler object, or a sequence of matplotlib colors like [‘red’, ‘blue’, ‘green’].

  • vmax (float or array-like or None) – Defines the lower limit of the color scale with values smaller than vmin sharing the same color. It can be a number, percentile string (‘pN’), function returning a desired value from the plot values, or None for automatic selection. For multiple plots, a list of vmin can be specified.

  • vmin (float or array-like or None) – Sets the upper limit of the color scale, with the same format and behavior as vmin.

  • vcenter (float or array-like or None) – Sets the center of the color scale, useful for diverging colormaps. It follows the same format and rules as vmin and vmax. Example: sc.pl.umap(adata, color=’TREM2’, vcenter=’p50’, cmap=’RdBu_r’).

  • norm (matplotlib.colors.Normalize or None) – The normalizing object which scales data, typically into the interval [0, 1]. If provided, vmax, vmin, and vcenter are ignored.

  • nticks (int, optional) – The number of ticks to be displayed on both the x and y axes. The matplotlib’s Axes.locator_params method is used for setting this property. Default is 3.

  • figsize (Tuple[float, float], optional) – Width and height of each subplot in inches. Default is (12, 4).

Returns:

fig, ax

Return type:

figure and axis elements of the plot.

Raises:
  • TypeError – If input parameters are not of the expected type.

  • ValueError – If input parameters do not have the expected values.

palantir.plot.plot_tsne_by_cell_sizes(data: DataFrame, tsne: DataFrame, fig: Figure | None = None, ax: Axes | None = None, vmin: float | None = None, vmax: float | None = None, figsize: Tuple[float, float] = (6, 6), s: float = 3, cmap: str = 'viridis', colorbar_label: str = 'Molecule Count') Tuple[Figure, Axes]View on GitHub

Plot tSNE projections of the data with cells colored by molecule counts.

Parameters:
  • data (pd.DataFrame) – Expression data, where each row is a cell and each column is a gene/feature.

  • tsne (pd.DataFrame) – tSNE coordinates with columns ‘x’ and ‘y’.

  • fig (Optional[plt.Figure], optional) – Matplotlib Figure object. If None, a new figure is created. Default is None.

  • ax (Optional[plt.Axes], optional) – Matplotlib Axes object. If None, a new Axes object is created. Default is None.

  • vmin (Optional[float], optional) – Minimum molecule count for plotting. Default is None.

  • vmax (Optional[float], optional) – Maximum molecule count for plotting. Default is None.

  • figsize (Tuple[float, float], optional) – Size of the figure (width, height) in inches. Default is (6, 6).

  • s (float, optional) – Size of the points in the scatter plot. Default is 3.

  • cmap (str, optional) – Colormap to use for the scatter plot. Default is ‘viridis’.

  • colorbar_label (str, optional) – Label for the colorbar. Default is ‘Molecule Count’.

Returns:

The figure and axes objects.

Return type:

Tuple[plt.Figure, plt.Axes]

palantir.plot.prepare_color_vector(ad: AnnData, color: str, mask: ndarray | None = None, layer: str | None = None, palette: str | Sequence[str] | None = None, na_color: str = 'lightgray')View on GitHub

Prepare the color vector for plotting.

Parameters:
  • ad (AnnData) – The annotated data matrix

  • color (str) – The color parameter

  • mask (np.ndarray, optional) – Boolean mask array

  • layer (str, optional) – The data layer to use

  • palette (str or Sequence[str], optional) – The color palette to use

  • na_color (str, optional) – The color for NA values

Returns:

Color vector and a flag indicating whether it’s categorical

Return type:

Tuple