spateo.plotting.static.utils ============================ .. py:module:: spateo.plotting.static.utils Classes ------- .. autoapisummary:: spateo.plotting.static.utils.Loess Functions --------- .. autoapisummary:: spateo.plotting.static.utils.is_gene_name spateo.plotting.static.utils.is_cell_anno_column spateo.plotting.static.utils.is_layer_keys spateo.plotting.static.utils.is_list_of_lists spateo.plotting.static.utils._get_adata_color_vec spateo.plotting.static.utils.map2color spateo.plotting.static.utils._to_hex spateo.plotting.static.utils._red spateo.plotting.static.utils._green spateo.plotting.static.utils._blue spateo.plotting.static.utils._embed_datashader_in_an_axis spateo.plotting.static.utils._get_extent spateo.plotting.static.utils._select_font_color spateo.plotting.static.utils._scatter_projection spateo.plotting.static.utils._vector_projection spateo.plotting.static.utils._streamlines_projection spateo.plotting.static.utils._geo_projection spateo.plotting.static.utils.plot_vectors spateo.plotting.static.utils._matplotlib_points spateo.plotting.static.utils.despline spateo.plotting.static.utils.despline_all spateo.plotting.static.utils.deaxis_all spateo.plotting.static.utils.minimal_xticks spateo.plotting.static.utils.minimal_yticks spateo.plotting.static.utils.set_spine_linewidth spateo.plotting.static.utils.scatter_with_colorbar spateo.plotting.static.utils.scatter_with_legend spateo.plotting.static.utils.set_colorbar spateo.plotting.static.utils.arrowed_spines spateo.plotting.static.utils.quiver_autoscaler spateo.plotting.static.utils.default_quiver_args spateo.plotting.static.utils._plot_traj spateo.plotting.static.utils.set_arrow_alpha spateo.plotting.static.utils.set_stream_line_alpha spateo.plotting.static.utils.save_fig spateo.plotting.static.utils.alpha_shape spateo.plotting.static.utils.plot_polygon spateo.plotting.static.utils.tricubic spateo.plotting.static.utils._convert_to_geo_dataframe spateo.plotting.static.utils.save_return_show_fig_utils spateo.plotting.static.utils._get_array_values spateo.plotting.static.utils.check_colornorm spateo.plotting.static.utils.deduplicate_kwargs spateo.plotting.static.utils._dendrogram_sig spateo.plotting.static.utils.dendrogram spateo.plotting.static.utils.plot_dendrogram Module Contents --------------- .. py:function:: is_gene_name(adata, var) .. py:function:: is_cell_anno_column(adata, var) .. py:function:: is_layer_keys(adata, var) .. py:function:: is_list_of_lists(list_of_lists) .. py:function:: _get_adata_color_vec(adata, layer, col) .. py:function:: map2color(val, min=None, max=None, cmap='viridis') .. py:function:: _to_hex(arr) .. py:function:: _red(x) .. py:function:: _green(x) .. py:function:: _blue(x) .. py:function:: _embed_datashader_in_an_axis(datashader_image, ax) .. py:function:: _get_extent(points) Compute bounds on a space with appropriate padding .. py:function:: _select_font_color(background) .. py:function:: _scatter_projection(ax, points, projection, **kwargs) .. py:function:: _vector_projection(ax, points: numpy.ndarray, vectors: numpy.ndarray, projection: str = '2d', geo: bool = False, **kwargs) Plot a 2D field of arrows over spatial transcriptomics data :param ax: Matplotlib axis object :param 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) :param vectors: Array of shape [n_samples, 2] or [n_samples, 3] containing the vector field :param projection: Either '2d' or '3d' to indicate if plot is 2D or 3D :param geo: Set True if plotting atop geometrical objects. If only generating a scatterplot, set False. :param \*\*kwargs: Additional keyword arguments provided to :func `ax.quiver()` .. py:function:: _streamlines_projection(ax, points: numpy.ndarray, vectors: numpy.ndarray, projection: str = '2d', geo: bool = False, **kwargs) Plot streamlines over spatial transcriptomics data :param ax: Matplotlib axis object :param 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) :param vectors: Array of shape [n_samples, 2] or [n_samples, 3] containing the vector field :param projection: Either '2d' or '3d' to indicate if plot is 2D or 3D :param geo: Set True if plotting atop geometrical objects. If only generating a scatterplot, set False. :param \*\*kwargs: Additional keyword arguments provided to :func `ax.streamplot()` .. py:function:: _geo_projection(ax, points, **kwargs) .. py:function:: plot_vectors(ax: Union[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) Wrapper for plotting vector fields. :param ax: Matplotlib axis object :param 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) :param V: Array of shape [n_samples, 2] or [n_samples, 3] containing the vector field :param 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') :param geo: Set True if plotting atop geometrical objects. If only generating a scatterplot, set False. .. py:function:: _matplotlib_points(points, ax=None, labels=None, values=None, highlights=None, cmap: str = 'Blues', color_key: Optional[str] = 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: Optional[numpy.ndarray] = None, V: Optional[numpy.ndarray] = None, vf_plot_method: str = 'cell', vf_kwargs: Optional[Dict] = None, **kwargs) .. py:function:: despline(ax=None) .. py:function:: despline_all(ax=None, sides=None) .. py:function:: deaxis_all(ax=None) .. py:function:: minimal_xticks(start, end) .. py:function:: minimal_yticks(start, end) .. py:function:: set_spine_linewidth(ax, lw) .. py:function:: scatter_with_colorbar(fig, ax, x, y, c, cmap, **kwargs) .. py:function:: scatter_with_legend(fig, ax, df, font_color, x, y, c, cmap, legend, **kwargs) .. py:function:: set_colorbar(ax, inset_dict={}) https://matplotlib.org/3.1.0/gallery/axes_grid1/demo_colorbar_with_inset_locator.html .. py:function:: arrowed_spines(ax, columns, background='white') https://stackoverflow.com/questions/33737736/matplotlib-axis-arrow-tip modified based on Answer 6 .. py:function:: quiver_autoscaler(X_emb, V_emb) 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` :rtype: The scale for quiver plot .. py:function:: default_quiver_args(arrow_size, arrow_len=None) .. py:function:: _plot_traj(y0, t, args, integration_direction, ax, color, lw, f) .. py:function:: set_arrow_alpha(ax=None, alpha=1) .. py:function:: set_stream_line_alpha(s=None, alpha=1) s has to be a StreamplotSet .. py:function:: save_fig(path=None, prefix=None, dpi=None, ext='pdf', transparent=True, close=True, verbose=True) 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. :type path: `string` prefix: `str` or `None` The prefix added to the figure name. This will be automatically set accordingly to the plotting function used. dpi: [ None | scalar > 0 | 'figure' ] The resolution in dots per inch. If None, defaults to rcParams["savefig.dpi"]. If 'figure', uses the figure's dpi value. ext: `string` (default='pdf') The file extension. This must be supported by the active matplotlib backend (see matplotlib.backends module). Most backends support 'png', 'pdf', 'ps', 'eps', and 'svg'. close: `boolean` (default=True) Whether to close the figure after saving. If you want to save_fig the figure multiple times (e.g., to multiple formats), you should NOT close it in between saves or you will have to re-plot it. verbose: boolean (default=True) Whether to print information about when and where the image has been saved. .. py:function:: alpha_shape(x, y, alpha) .. py:function:: plot_polygon(polygon, margin=1, fc='#999999', ec='#000000', fill=True, ax=None, **kwargs) .. py:function:: tricubic(x) .. py:class:: Loess(xx, yy, degree=1) Bases: :py:obj:`object` .. py:method:: normalize_array(array) :staticmethod: .. py:attribute:: degree :value: 1 .. py:method:: get_min_range(distances, window) :staticmethod: .. py:method:: get_weights(distances, min_range) :staticmethod: .. py:method:: normalize_x(value) .. py:method:: denormalize_y(value) .. py:method:: estimate(x, window, use_matrix=False, degree=1) .. py:function:: _convert_to_geo_dataframe(adata, basis) .. py:function:: 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]) -> Optional[Tuple] .. py:function:: _get_array_values(X: Union[numpy.ndarray, scipy.sparse.base.spmatrix], dim_names: pandas.Index, keys: List[str], axis: typing_extensions.Literal[0, 1], backed: bool) Subset and reorder data array, given array and corresponding array index. :param X: np.ndarray or scipy sparse matrix :param dim_names: pd.Index Names of :param keys: list of str Index names to subset :param axis: int, 0 or 1 Subset rows or columns of 'X' (0 for rows, 1 for columns) :param backed: bool Interfaces w/ AnnData objects; is True if AnnData is backed to disk :returns: np.ndarray :rtype: matrix .. py:function:: check_colornorm(vmin: Union[None, float] = None, vmax: Union[None, float] = None, vcenter: Union[None, float] = None, norm: Union[None, matplotlib.colors.Normalize] = None) When plotting continuous variables, configure a normalizer object for the purposes of mapping the data to varying color intensities. :param vmin: optional float The data value that defines 0.0 in the normalization. Defaults to the min value of the dataset. :param vmax: optional float The data value that defines 1.0 in the normalization. Defaults to the the max value of the dataset. :param vcenter: optional float The data value that defines 0.5 in the normalization :param 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. :rtype: normalize .. py:function:: deduplicate_kwargs(kwargs_dict, **kwargs) 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. :param kwargs_dict: dict Each key is a variable name and each value is the value of that variable :param kwargs: Any additional keyword arguments, the keywords of which may or may not already be in 'kwargs_dict' .. py:function:: _dendrogram_sig(data: numpy.ndarray, method: str, **kwargs) -> Tuple[List[int], List[int], List[int], List[int]] .. py:function:: dendrogram(adata: anndata.AnnData, cat_key: str, n_pcs: int = 30, use_rep: Union[None, str] = None, var_names: Union[None, List[str]] = None, cor_method: str = 'pearson', linkage_method: str = 'complete', optimal_ordering: bool = False, key_added: Union[None, str] = None, inplace: bool = True) -> Optional[Dict[str, Any]] 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. :param adata: object of class `anndata.AnnData` :param cat_key: Name of key in .obs specifying group labels for each sample :param n_pcs: Number of principal components to use in computing hierarchical clustering :param use_rep: Entry in .obsm to use for computing hierarchical clustering :param var_names: List of genes to define a subset of 'adata' to compute hierarchical clustering directly on expression values. :param cor_method: Correlation method to use. Options are 'pearson', 'kendall', and 'spearman' :param linkage_method: Linkage method to use. See :func:`scipy.cluster.hierarchy.linkage` for more information. :param optimal_ordering: Same as the optimal_ordering argument of :func:`scipy.cluster.hierarchy.linkage` which reorders the linkage matrix so that the distance between successive leaves is minimal. :param 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}']`. :param 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]`. .. py:function:: plot_dendrogram(dendro_ax: matplotlib.axes.Axes, adata: anndata.AnnData, cat_key: str, dendrogram_key: Union[None, str] = None, orientation: typing_extensions.Literal[top, bottom, left, right] = 'right', remove_labels: bool = True, ticks: Union[None, Collection[float]] = None) Plots dendrogram on the provided Axes, using the dendrogram information stored in `.uns[dendrogram_key]` :param dendro_ax: object of class `matplotlib.axes.Axes` :param adata: object of class `anndata.AnnData` Contains dendrogram information as well as the data that will be plotted (and was used to hierarchically cluster) :param cat_key: Key in .obs containing category labels for all samples :param dendrogram_key: :param orientation: Specifies dendrogram placement relative to the plotting window. Options: 'top', 'bottom', 'left', 'right' :param remove_labels: Removes labels along the side that dendrogram is on, if any :param ticks: Assumes original ticks come from `scipy.cluster.hierarchy.dendrogram`, but if not can also pass a list of custom tick values.