spateo.plotting.static.utils#

Module Contents#

Classes#

Functions#

is_gene_name(adata, var)

is_cell_anno_column(adata, var)

is_layer_keys(adata, var)

is_list_of_lists(list_of_lists)

_get_adata_color_vec(adata, layer, col)

map2color(val[, min, max, cmap])

_to_hex(arr)

_red(x)

_green(x)

_blue(x)

_embed_datashader_in_an_axis(datashader_image, ax)

_get_extent(points)

Compute bounds on a space with appropriate padding

_select_font_color(background)

_scatter_projection(ax, points, projection, **kwargs)

_vector_projection(ax, points, vectors[, projection, geo])

Plot a 2D field of arrows over spatial transcriptomics data

_streamlines_projection(ax, points, vectors[, ...])

Plot streamlines over spatial transcriptomics data

_geo_projection(ax, points, **kwargs)

plot_vectors(ax, points, V[, vf_plot_method, ...])

Wrapper for plotting vector fields.

_matplotlib_points(points[, ax, labels, values, ...])

despline([ax])

despline_all([ax, sides])

deaxis_all([ax])

minimal_xticks(start, end)

minimal_yticks(start, end)

set_spine_linewidth(ax, lw)

scatter_with_colorbar(fig, ax, x, y, c, cmap, **kwargs)

scatter_with_legend(fig, ax, df, font_color, x, y, c, ...)

set_colorbar(ax[, inset_dict])

https://matplotlib.org/3.1.0/gallery/axes_grid1/demo_colorbar_with_inset_locator.html

arrowed_spines(ax, columns[, background])

https://stackoverflow.com/questions/33737736/matplotlib-axis-arrow-tip

quiver_autoscaler(X_emb, V_emb)

Function to automatically calculate the value for the scale parameter of quiver plot, adapted from scVelo

default_quiver_args(arrow_size[, arrow_len])

_plot_traj(y0, t, args, integration_direction, ax, ...)

set_arrow_alpha([ax, alpha])

set_stream_line_alpha([s, alpha])

s has to be a StreamplotSet

save_fig([path, prefix, dpi, ext, transparent, close, ...])

Save a figure from pyplot.

alpha_shape(x, y, alpha)

plot_polygon(polygon[, margin, fc, ec, fill, ax])

tricubic(x)

_convert_to_geo_dataframe(adata, basis)

save_return_show_fig_utils(→ Optional[Tuple])

_get_array_values(X, dim_names, keys, axis, backed)

Subset and reorder data array, given array and corresponding array index.

check_colornorm([vmin, vmax, vcenter, norm])

When plotting continuous variables, configure a normalizer object for the purposes of mapping the data to varying

deduplicate_kwargs(kwargs_dict, **kwargs)

Given a dictionary of plot parameters (kwargs_dict) and any number of additional keyword arguments,

_dendrogram_sig(→ Tuple[List[int], List[int], ...)

dendrogram(→ Optional[Dict[str, Any]])

Computes a hierarchical clustering for the categories given by 'cat_key'.

plot_dendrogram(dendro_ax, adata, cat_key[, ...])

Plots dendrogram on the provided Axes, using the dendrogram information stored in .uns[dendrogram_key]

spateo.plotting.static.utils.is_gene_name(adata, var)[source]#
spateo.plotting.static.utils.is_cell_anno_column(adata, var)[source]#
spateo.plotting.static.utils.is_layer_keys(adata, var)[source]#
spateo.plotting.static.utils.is_list_of_lists(list_of_lists)[source]#
spateo.plotting.static.utils._get_adata_color_vec(adata, layer, col)[source]#
spateo.plotting.static.utils.map2color(val, min=None, max=None, cmap='viridis')[source]#
spateo.plotting.static.utils._to_hex(arr)[source]#
spateo.plotting.static.utils._red(x)[source]#
spateo.plotting.static.utils._green(x)[source]#
spateo.plotting.static.utils._blue(x)[source]#
spateo.plotting.static.utils._embed_datashader_in_an_axis(datashader_image, ax)[source]#
spateo.plotting.static.utils._get_extent(points)[source]#

Compute bounds on a space with appropriate padding

spateo.plotting.static.utils._select_font_color(background)[source]#
spateo.plotting.static.utils._scatter_projection(ax, points, projection, **kwargs)[source]#
spateo.plotting.static.utils._vector_projection(ax, points: numpy.ndarray, vectors: numpy.ndarray, projection: str = '2d', geo: bool = False, **kwargs)[source]#

Plot a 2D field of arrows over spatial transcriptomics data

Parameters:
ax

Matplotlib axis object

points

Point coordinates of shape [n_samples, 2], either grid coordinates (for grid or streamlines plots) or coordinates of the cells themselves (for cell plots)

vectors

Array of shape [n_samples, 2] or [n_samples, 3] containing the vector field

projection

Either ‘2d’ or ‘3d’ to indicate if plot is 2D or 3D

geo

Set True if plotting atop geometrical objects. If only generating a scatterplot, set False.

**kwargs

Additional keyword arguments provided to :func ax.quiver()

spateo.plotting.static.utils._streamlines_projection(ax, points: numpy.ndarray, vectors: numpy.ndarray, projection: str = '2d', geo: bool = False, **kwargs)[source]#

Plot streamlines over spatial transcriptomics data

Parameters:
ax

Matplotlib axis object

points

Point coordinates of shape [n_samples, 2], either grid coordinates (for grid or streamlines plots) or coordinates of the cells themselves (for cell plots)

vectors

Array of shape [n_samples, 2] or [n_samples, 3] containing the vector field

projection

Either ‘2d’ or ‘3d’ to indicate if plot is 2D or 3D

geo

Set True if plotting atop geometrical objects. If only generating a scatterplot, set False.

**kwargs

Additional keyword arguments provided to :func ax.streamplot()

spateo.plotting.static.utils._geo_projection(ax, points, **kwargs)[source]#
spateo.plotting.static.utils.plot_vectors(ax: matplotlib.pyplot.Axes | mpl_toolkits.mplot3d.Axes3D, points: numpy.ndarray, V: numpy.ndarray, vf_plot_method: str = 'cell', projection: str = '2d', geo: bool = False, **kwargs)[source]#

Wrapper for plotting vector fields.

Parameters:
ax

Matplotlib axis object

points

Point coordinates of shape [n_samples, 2], either grid coordinates (for grid or streamlines plots) or coordinates of the cells themselves (for cell plots)

V

Array of shape [n_samples, 2] or [n_samples, 3] containing the vector field

vf_plot_method

‘grid’ or ‘streamplot’ to indicate if plot should be vectors coming from the cells themselves (‘cell’), vectors coming from vertices of a grid (‘grid’) or streamlines coming from vertices of a grid ( ‘streamplot’)

geo

Set True if plotting atop geometrical objects. If only generating a scatterplot, set False.

spateo.plotting.static.utils._matplotlib_points(points, ax=None, labels=None, values=None, highlights=None, cmap: str = 'Blues', color_key: str | None = None, color_key_cmap: str = 'Spectral', background: str = 'white', width: int = 7, height: int = 5, show_legend: bool = True, vmin: float = 2, vmax: float = 98, sort: str = 'raw', frontier: bool = False, contour: bool = False, ccmap=None, calpha: float = 0.4, sym_c: bool = False, inset_dict={}, show_colorbar: bool = True, projection=None, geo: bool = False, X_grid: numpy.ndarray | None = None, V: numpy.ndarray | None = None, vf_plot_method: str = 'cell', vf_kwargs: Dict | None = None, **kwargs)[source]#
spateo.plotting.static.utils.despline(ax=None)[source]#
spateo.plotting.static.utils.despline_all(ax=None, sides=None)[source]#
spateo.plotting.static.utils.deaxis_all(ax=None)[source]#
spateo.plotting.static.utils.minimal_xticks(start, end)[source]#
spateo.plotting.static.utils.minimal_yticks(start, end)[source]#
spateo.plotting.static.utils.set_spine_linewidth(ax, lw)[source]#
spateo.plotting.static.utils.scatter_with_colorbar(fig, ax, x, y, c, cmap, **kwargs)[source]#
spateo.plotting.static.utils.scatter_with_legend(fig, ax, df, font_color, x, y, c, cmap, legend, **kwargs)[source]#
spateo.plotting.static.utils.set_colorbar(ax, inset_dict={})[source]#

https://matplotlib.org/3.1.0/gallery/axes_grid1/demo_colorbar_with_inset_locator.html

spateo.plotting.static.utils.arrowed_spines(ax, columns, background='white')[source]#

https://stackoverflow.com/questions/33737736/matplotlib-axis-arrow-tip modified based on Answer 6

spateo.plotting.static.utils.quiver_autoscaler(X_emb, V_emb)[source]#

Function to automatically calculate the value for the scale parameter of quiver plot, adapted from scVelo :param X_emb: X, Y-axis coordinates :type X_emb: np.ndarray :param V_emb: Velocity (U, V) values on the X, Y-axis :type V_emb: np.ndarray

Return type:

The scale for quiver plot

spateo.plotting.static.utils.default_quiver_args(arrow_size, arrow_len=None)[source]#
spateo.plotting.static.utils._plot_traj(y0, t, args, integration_direction, ax, color, lw, f)[source]#
spateo.plotting.static.utils.set_arrow_alpha(ax=None, alpha=1)[source]#
spateo.plotting.static.utils.set_stream_line_alpha(s=None, alpha=1)[source]#

s has to be a StreamplotSet

spateo.plotting.static.utils.save_fig(path=None, prefix=None, dpi=None, ext='pdf', transparent=True, close=True, verbose=True)[source]#

Save a figure from pyplot. code adapated from http://www.jesshamrick.com/2012/09/03/saving-figures-from-pyplot/ :param path: The path (and filename, without the extension) to save_fig the

figure to.

spateo.plotting.static.utils.alpha_shape(x, y, alpha)[source]#
spateo.plotting.static.utils.plot_polygon(polygon, margin=1, fc='#999999', ec='#000000', fill=True, ax=None, **kwargs)[source]#
spateo.plotting.static.utils.tricubic(x)[source]#
class spateo.plotting.static.utils.Loess(xx, yy, degree=1)[source]#

Bases: object

static normalize_array(array)[source]#
static get_min_range(distances, window)[source]#
static get_weights(distances, min_range)[source]#
normalize_x(value)[source]#
denormalize_y(value)[source]#
estimate(x, window, use_matrix=False, degree=1)[source]#
spateo.plotting.static.utils._convert_to_geo_dataframe(adata, basis)[source]#
spateo.plotting.static.utils.save_return_show_fig_utils(save_show_or_return: typing_extensions.Literal[save, show, return, both, all], show_legend: bool, background: str, prefix: str, save_kwargs: Dict, total_panels: int, fig: matplotlib.figure.Figure, axes: matplotlib.axes.Axes, return_all: bool, return_all_list: Union[List, Tuple, None]) Tuple | None[source]#
spateo.plotting.static.utils._get_array_values(X: numpy.ndarray | scipy.sparse.base.spmatrix, dim_names: pandas.Index, keys: List[str], axis: typing_extensions.Literal[0, 1], backed: bool)[source]#

Subset and reorder data array, given array and corresponding array index.

Parameters:
X

np.ndarray or scipy sparse matrix

dim_names

pd.Index Names of

keys

list of str Index names to subset

axis

int, 0 or 1 Subset rows or columns of ‘X’ (0 for rows, 1 for columns)

backed

bool Interfaces w/ AnnData objects; is True if AnnData is backed to disk

Returns:

np.ndarray

Return type:

matrix

spateo.plotting.static.utils.check_colornorm(vmin: None | float = None, vmax: None | float = None, vcenter: None | float = None, norm: None | matplotlib.colors.Normalize = None)[source]#

When plotting continuous variables, configure a normalizer object for the purposes of mapping the data to varying color intensities.

Parameters:
vmin

optional float The data value that defines 0.0 in the normalization. Defaults to the min value of the dataset.

vmax

optional float The data value that defines 1.0 in the normalization. Defaults to the the max value of the dataset.

vcenter

optional float The data value that defines 0.5 in the normalization

norm

optional matplotlib.colors.Normalize object Optional already-initialized normalizing object that scales data, typically into the interval [0, 1], for the purposes of mapping to color intensities for plotting. Do not pass both ‘norm’ and ‘vmin’/’vmax’, etc.

Returns:

matplotlib.colors.Normalize object

The normalizing object that scales data, typically into the interval [0, 1], for the purposes of mapping to color intensities for plotting.

Return type:

normalize

spateo.plotting.static.utils.deduplicate_kwargs(kwargs_dict, **kwargs)[source]#

Given a dictionary of plot parameters (kwargs_dict) and any number of additional keyword arguments, merge the parameters into a single consolidated dictionary to avoid argument duplication errors. If kwargs_dict contains a key that matches any of the additional keyword arguments, only the value in kwargs_dict is kept.

Parameters:
kwargs_dict

dict Each key is a variable name and each value is the value of that variable

kwargs

Any additional keyword arguments, the keywords of which may or may not already be in ‘kwargs_dict’

spateo.plotting.static.utils._dendrogram_sig(data: numpy.ndarray, method: str, **kwargs) Tuple[List[int], List[int], List[int], List[int]][source]#
spateo.plotting.static.utils.dendrogram(adata: anndata.AnnData, cat_key: str, n_pcs: int = 30, use_rep: None | str = None, var_names: None | List[str] = None, cor_method: str = 'pearson', linkage_method: str = 'complete', optimal_ordering: bool = False, key_added: None | str = None, inplace: bool = True) Dict[str, Any] | None[source]#

Computes a hierarchical clustering for the categories given by ‘cat_key’.

By default, the PCA representation is used unless .X has less than 50 variables.

Alternatively, a list of var_names (e.g. genes) can be given. If this is the case, will subset to these features and use them for the dendrogram.

Parameters:
adata

object of class anndata.AnnData

cat_key

Name of key in .obs specifying group labels for each sample

n_pcs

Number of principal components to use in computing hierarchical clustering

use_rep

Entry in .obsm to use for computing hierarchical clustering

var_names

List of genes to define a subset of ‘adata’ to compute hierarchical clustering directly on expression values.

cor_method

Correlation method to use. Options are ‘pearson’, ‘kendall’, and ‘spearman’

linkage_method

Linkage method to use. See scipy.cluster.hierarchy.linkage() for more information.

optimal_ordering

Same as the optimal_ordering argument of scipy.cluster.hierarchy.linkage() which reorders the linkage matrix so that the distance between successive leaves is minimal.

key_added

Sets key in .uns in which dendrogram information is saved. By default, the dendrogram information is added to .uns[f’dendrogram_{cat_key}’].

inplace

If True, adds dendrogram information to adata.uns[key_added], else this function returns the information.

Returns:

If inplace=False, returns dendrogram information, else adata object is updated in place with information stored in adata.uns[key_added].

spateo.plotting.static.utils.plot_dendrogram(dendro_ax: matplotlib.axes.Axes, adata: anndata.AnnData, cat_key: str, dendrogram_key: None | str = None, orientation: typing_extensions.Literal[top, bottom, left, right] = 'right', remove_labels: bool = True, ticks: None | Collection[float] = None)[source]#

Plots dendrogram on the provided Axes, using the dendrogram information stored in .uns[dendrogram_key]

Parameters:
dendro_ax

object of class matplotlib.axes.Axes

adata

object of class anndata.AnnData Contains dendrogram information as well as the data that will be plotted (and was used to hierarchically cluster)

cat_key

Key in .obs containing category labels for all samples

dendrogram_key

orientation

Specifies dendrogram placement relative to the plotting window. Options: ‘top’, ‘bottom’, ‘left’, ‘right’

remove_labels

Removes labels along the side that dendrogram is on, if any

ticks

Assumes original ticks come from scipy.cluster.hierarchy.dendrogram, but if not can also pass a list of custom tick values.