new_visiumHD(path_image_fullres: str, path_input_data: str, path_output: str, name: str, crop_images=True, properties: dict = None, on_tissue_only=True, min_reads_in_spot=1, min_reads_gene=10, fluorescence=False, plot_qc=True)[source]
  • Loads images, data and metadata.

  • Initializes the connection from the data and metadata to the images coordinates

  • Adds basic QC to the metadata (nUMI, mitochondrial %)

Parameters:
  • path_input_fullres_image (str) - path of the full resolution microscopy image

  • path_input_data (str) - folder with outs of the Visium. Typically square_002um (with h5 files and with folders filtered_feature_bc_matrix, spatial)

  • path_output (str) - path where to save plots and files

  • name (str) - name of the instance

  • crop_images (bool) - crop the regions outside of the spots cover area

  • properties (dict) - can be any metadata, such as organism, organ, sample_id. Organism is recomended (i.e human or mouse) for case-sensitivity correction and QC of mitochondrial reads.

  • on_tissue_only (bool) - remove spots that are not classified as “on tissue”

  • min_reads_in_spot (int) - filter out spots with less than X UMIs

  • min_reads_gene (int) - filter out gene that is present in less than X spots

  • fluorescence - either False for H&E, or a dict of channel names and colors. color can be None. Example {“DAPI”:”blue”}

  • plot_qc (bool) - plot QC when object is being created

Returns HiVis instance

new_merfish(path, bin_size_um, name, path_output, fluorescence, properties=None, downscale_factor=4)[source]

Load MERFISH data into a HiVis object.

Parameters:
  • path (str or pathlib.Path) - Path to the Xenium output directory. Must contain experiment.xenium and a morphology_focus subdirectory with OME-TIFF morphology images.

  • bin_size_um (float) - Spatial bin size in micrometers used to aggregate transcript counts into a grid.

  • name (str) - Name to assign to the returned HiVis object.

  • path_output (str or pathlib.Path) - Output directory passed to the HiVis object for saving results/artifacts.

  • fluorescence (dict) - Dict of channel names and colors. color can be None. Example {“DAPI”:”blue”}

  • properties (dict, optional) - Metadata passed to the HiVis object.

  • downscale_factor (int) - Downscaling factor applied when generating the downscaled image (default: 4).

Returns:

HiVis instance.

new_xenium(path, bin_size_um, name, path_output, fluorescence, properties=None, downscale_factor=1)[source]

Load 10x Genomics Xenium data into a HiVis object.

This function: - Reads Xenium transcript points via spatialdata_io.xenium and aggregates them into a binned count matrix (AnnData) using bin_size_um. - Loads Xenium morphology OME-TIFF images from the morphology_focus directory and stacks them into a single (Y, X, C) array.

Parameters:
  • path (str or pathlib.Path) - Path to the Xenium output directory. Must contain experiment.xenium and a morphology_focus subdirectory with OME-TIFF morphology images.

  • bin_size_um (float) - Spatial bin size in micrometers used to aggregate transcript counts into a grid.

  • name (str) - Name to assign to the returned HiVis object.

  • path_output (str or pathlib.Path) - Output directory passed to the HiVis object for saving results/artifacts.

  • fluorescence - either False for H&E, or a dict of channel names and colors. color can be None. Example {“DAPI”:”blue”}

  • properties (dict, optional) - Metadata passed to the HiVis object.

  • downscale_factor (int) - Downscaling factor applied when generating the downscaled image.

Returns:

HiVis instance.

new_stereoseq(path_transcripts, path_image, bin_size_um, name, path_output, fluorescence, microns_per_pixel=0.5, properties=None, downscale_factor=1, flip_img=True, exp_col='MIDCounts')[source]

Loads Stereoseq data into HiVis.

Parameters:

path_transcripts (str): Path to the gene count table (csv/tsv). path_image (str): Path to the fullres TIFF image. bin_size_um (float): Desired bin size in microns. name (str): Sample name. path_output (str): Output directory. fluorescence (dict): Dictionary of channel names. microns_per_pixel (float): Resolution of the input image (default 0.5 for standard Stereo-seq). properties (dict): Optional metadata (e.g., organism). downscale_factor (int): Factor to downscale the image for visualization. flip_img (bool) - flip by 270 degrees and mirror the image. exp_col (str): Name of column in the data which stores the count

Returns: HiVis object

load(filename, directory='')[source]

loads an instance from a pickle format, that have been saved via HiVis.save()

Parameters:
  • filename (str)- full path of pkl file, or just the filename if directory is specified

Returns HiVis instance

HiVis

Main class. Stores the data and images of the VisiumHD, enables plotting via HiVis.plot, and can store Aggregation instances in HiVis.agg. To make a new class, call the new() function.

General methods

HiVis.copy(new_name=None, new_out_path=False, full=False)[source]

Creates a deep copy of the instance. if new_name is specified, renames the object and changes the path_output. If full is False, the name will be added to the current (previous) name.

Returns new HiVis instance

HiVis.recolor(fluorescence=None, normalization_method='percentile')[source]

Recolors a flurescence image

Parameters:
  • fluorescence is either list of colors or dict {channel: color…}. color can be None.

  • normalization_method - {“percentile”, “histogram”,”clahe”,”sqrt” or None for minmax}

HiVis.rename(new_name: str, new_out_path=False, full=False)[source]

Renames the object and changes the path_output. If full is False, the name will be added to the current (previous) name

HiVis.combine(other)[source]

Combines two HiVis objects into a single HiVis. Spatial plots and analysis will be disabled.

HiVis.update_meta(name: str, values: dict, type_='obs')[source]

Updates values in metadata (obs or var)

Parameters:
  • name (str) - name of metadata

  • values (dict) -{old_value:new_value}

  • type_ - either “obs” or “var”

HiVis.head(n=5)[source]

Returns HiVis.adata.obs.head(n), where n is number of rows

HiVis.update(agg=False)[source]

Updates the methods in the instance. Should be used after modifying the source code in the class

Segmentations, annotations, masks

HiVis.add_mask(mask_path: str, name: str, plot=True, cmap='Paired', downscale=10)[source]

assigns each spot a value based on mask (image).

Parameters:
  • mask_path (str) - path to mask image

  • name (str) - name of the mask (that will be called in the metadata)

  • plot (bool) - plot the mask

  • cmap (str) - colormap for plotting

  • downscale (int) - sownscale the plot. only relevent if plot=True

Returns the mask (np.array)

HiVis.add_annotations(path: str, name: str, measurements=True)[source]

Adds annotations made in Qupath (geojson)

Parameters:
  • path (str) - path to geojson file

  • name (str) - name of the annotation (that will be called in the obs)

  • measurements (bool) - include measurements columns

HiVis.agg_cells(input_df, name='SC', obs2add=None, obs2agg=None, geojson_path=None)[source]

Adds Aggregation object to self.agg[name], based on CSV output of Qupath pipeline.

Parameters:
  • input_df (pd.DataFrame) - output of Qupath pipeline

  • name (str) - name to store the Aggregation in. Can be accessed via HiVis.agg[name]

  • obs2agg - what obs to aggregate from the HiVis. Can be a list of column names. numeric columns will be summed, categorical will be the mode. Can be a dictionary specifying the aggregation function. examples: {“value_along_axis”:np.median} or {“value_along_axis”:[np.median,np.mean]}

  • obs2add (list) - which columns from input_df should be copied to the Aggregation.adata.obs

  • nuc_only (bool) - aggregate only spots in nuclei

  • geojson_path (str) - path to geojson file that was exported from Qupath

HiVis.agg_from_annotations(annotation_id_col, name='SC', obs2agg=None, geojson_path=None)[source]

Adds Aggregation object to self.agg[name], based on annotation column.

Parameters:
  • annotation_id_col (str) - column name that the aggregation will be based on

  • name (str) - name to store the Aggregation in. Can be accessed via HiVis.agg[name]

  • obs2agg - what obs to aggregate from the HiVis. Can be a list of column names. numeric columns will be summed, categorical will be the mode. Can be a dictionary specifying the aggregation function. examples: {“value_along_axis”:np.median} or {“value_along_axis”:[np.median,np.mean]}

  • geojson_path (str) - path to geojson file that was used to create the annotations

Analyses

Methods are called by HiVis.analysis.

AnalysisVisium.qc(save=False, figsize=(8, 8))[source]

Plots basic QC (spatial, nUMI, mitochondrial %)

Parameters:
  • save (bool) - save the plot in HiVis.path_output

AnalysisVisium.dge(column, group1, group2=None, method='fisher_exact', two_sided=False, umi_thresh=0, inplace=False, layer=None)[source]

Runs differential gene expression analysis between two groups. Values will be saved in self.main.var: expression_mean, log2fc, pval

Parameters:
  • column (str) - which column in obs has the groups classification

  • group1 (str) - specific value in the “column”

  • group2 (str) - specific value in the “column”. if None, will run against all other values, and will be called “rest”

  • method (str) - one of [“fisher_exact”, “wilcox”, “t_test”]

  • two_sided (bool) - if one sided, will give the pval for each group, and the minimal of both groups (which will also be FDR adjusted)

  • umi_thresh (int) - use only spots with more UMIs than this number

  • inplace (bool) - modify the adata.var with log2fc, pval and expression columns

  • layer (str) - which layer in the AnnData to use

Returns the DGE results (pd.DataFrame)

AnalysisVisium.pseudobulk(by=None, layer=None, normalize=True)[source]

Sums the gene expression for each group in a single obs.

Parameters:

  • by (str) - return a dataframe, each column is a value in “by” (for example cluster), rows are genes. If None, will return the mean expression of every gene.

  • layer (str) - which layer in adata to use.

  • normalize (bool) - normalize the values to the sum of each group. if False, values will be the sum of each category.

Returns the gene expression for each group (pd.DataFrame)

AnalysisVisium.noise_mean_curve(layer=None, inplace=False, poly_deg=4)[source]

Generates a noise-mean curve of the data and calculates residuals.

Parameters:
  • layer - which layer in the AnnData to use

  • inplace (bool) - add the mean_expression, cv and residuals to VAR

  • poly_deg (int) - degree of polynomial fit. if 1, will be a linear model

Returns dataframe with expression, CV and residuals of each gene (pd.DataFrame).

AnalysisVisium.cor(what, self_corr_value=None, normalize=True, layer: str = None, inplace=False)[source]

Calculates gene(s) correlation.

Parameters:
  • what (str or list) - if str, computes Spearman correlation of a given gene with all genes. if list, will compute correlation between all genes in the list

  • self_corr_value - replace the correlation of the gene with itself by this value

  • normalize (bool) - normalize expression before computing correlation

  • layer (str) - which layer in the AnnData to use

  • inplace (bool) - add the correlation to VAR

Returns dataframe of spearman correlation between genes (pd.DataFrame)

AnalysisVisium.score_genes(gene_list: list, score_name: str, z_normalize=False)[source]

Assigns score for each bin, based on a list of genes.

Parameters:
  • gene_list (list) - list of genes

  • score_name (str) - name of column that will store the score in self.main.adata.obs

  • z_normalize (bool) - Z transform the score values

returns score values (pd.Series)

AnalysisVisium.smooth(what, radius, method='mean', new_col_name=None, layer=None, **kwargs)[source]

Applies median smoothing to the specified column in adata.obs using spatial neighbors.

Parameters:
  • what (str) - what to smooth. either a gene name or column name from self.main.adata.obs

  • radius (float) - in microns

  • method - [“mode”, “median”, “mean”, “gaussian”, “log”]

  • new_col_name (str) - Optional custom name for the output column

  • layer (str) - which layer in the AnnData to use

  • **kwargs - Additional Parameters for specific methods (e.g., sigma for gaussian, offset for log).

returns smoothed values (pd.Series)

AnalysisVisium.compute_distances(agg_name, dist_col_name=None, nearest_col_name=None)[source]

Compute distances of each bin to the nearest aggregation.

Parameters:
  • agg_name (str) - name of agg

  • dist_col_name (str) - Name of column to save distance to. default is dist_to_{agg_name}

  • nearest_col_name (str) - Name of column to save the closest aggregation name

Plots

Methods are called by HiVis.plot.

PlotVisium.spatial(what=None, exact=None, image=True, img_resolution=None, ax=None, title=None, cmap='winter', legend=True, alpha=1, figsize=(7, 7), save=False, brightness=1, contrast=1, layer=None, xlim=None, ylim=None, scalebar=True, legend_title=None, axis_labels=False, pad=False, show_zeros=False, rasterize=False)[source]

Plots the image, and/or data/metadata (spatial plot)

Parameters:
  • what (str) - what to plot. can be metadata (obs/var colnames or a gene)

  • exact (bool) - plot the squares at the exact size. more time costly

  • image (bool) - plot image

  • img_resolution - “low”,”high”,”full”. If None, will determine automatically

  • ax - matplotlib ax, if not passed, new figure will be created with size=figsize

  • cmap - colormap to use. can be string, or a list of colors

  • layer (str) - which layer in adata to use

  • title, legend_title, axis_labels - strings

  • legend (bool)- show legend

  • xlim, ylim - two values each, in microns, example [50,100]

  • scalebar - either the length in microns (or None for 0.2 of xlim length), or False to not show the scalebar, or a dict with arguments for add_scalebar(), such as:

    {length_microns=None, text=True, line_width=4, color=’white’, text_offset=0.035}

  • pad (float) - scale the size of dots

  • alpha (float) - transparency of scatterplot. value between 0 and 1

  • save (bool) - save the image

  • brightness (float) - increases brigtness, for example 0.2.

  • contrast (float) - > 1 increases contrast, < 1 decreases.

  • rasterize - Rasterize elements for smaller figure size

Returns ax

PlotVisium.hist(what, bins=20, xlim=None, title=None, ylab=None, xlab=None, ax=None, layer=None, save=False, figsize=(7, 7), cmap=None, color='blue', cropped=False)[source]

Plots histogram of data or metadata. if categorical, will plot barplot

Parameters:
  • what (str) - what to plot. can be metadata (obs/var colnames or a gene)

  • bins (int) - number of bins of the histogram

  • ax (optional) - matplotlib ax, if not passed, new figure will be created with size=figsize

  • cmap - colorbar to use. Can be string, list of colors, or dictionary of {val:color}. overrides the color argument for barplot

  • color (str)- color of the histogram

  • layer (str) - which layer in adata to use

  • title, xlab, ylab - strings

  • xlim - two values, where to crop the x axis, example [50,100]

  • save (bool)- save the image

  • cropped (bool) - if False and plot.spatial was run with xlim, ylim hist will be on cropped area

Returns ax

PlotVisium.cor(what, number_of_genes=10, normalize=True, self_corr_value=numpy.nan, layer=None, cluster=True, ax=None, figsize=(7, 7), save=False, size=15, text=True, cmap='copper', legend=True, legend_title=None, print_=False)[source]

Plots correlation of a gene with all genes, or a correlation matrix between list of genes.

Parameters:
  • what - either a str or a list. if a single genes, will plot correlation to all other genes. in this case, will pull and save the data to Aggregation.adata.var.if a list of genes, will plot a heatmap.

  • number_of_genes (int) - only applicable if what is a single gene. how many gene names (text) to add to the plot.

  • cluster (bool) - only applicable if what is a list of genes. whether to cluster the heatmap

  • normalize (bool) - normalize data before performing correlation

  • layer (str)- which layer to use from the self.adata. If None, will use X

  • ax (optional) - matplotlib ax, if not passed, new figure will be created with size=figsize

  • cmap - colormap for scatterplot / heatmap. in heatmap can be list of colors.

  • size (int) - size of spots in scatterplot.

  • save (bool) - svae the plot

  • text, legend, legend_title - cosmetic Parameters

  • print_ (bool) - print most correlated genes

Returns ax

PlotVisium.noise_mean_curve(poly_deg=4, signif_thresh=0.999, layer=None, save=False, ax=None, text=True, figsize=(7, 7), color='black', size=10, cmap='cool', repel=False, title=None, legend=True, fit_color=None)[source]

Generates a noise-mean curve of the data.

Parameters:
  • poly_deg (int > 0) - degree of polynomial to fit the data.

  • signif_thresh (float) - add text for genes in this residual percentile

  • layer (str) - which layer in the AnnData to use

  • ax (optional) - matplotlib ax, if not passed, new figure will be created with size=figsize

  • cmap - colormap for scatterplot. can be name of colormap, or list of colors

  • size (int) - size of dots in scatterplot

  • save (bool) - svae the plot

  • repel (bool) - repel text

  • fit_color (str) - color to plot the fitted curve

  • title, color, legend - cosmetic parameters

returns ax

PlotVisium.save(figname: str, fig=None, ax=None, open_file=False, formats=['pdf', 'svg', 'png'], dpi=300, pad_inches=0)[source]

Saves a figure or ax.

Parameters:
  • figname (str) - name of plot

  • fig (optional) - plt.Figure object to save, can be a dataframe for writing csv.

  • ax - ax to save. if not passed, will use self.current_ax

  • open_file (bool) - open the file

  • formats (str or list) - format(s) of file to save

  • dpi (int) - resolution in dot per inch

  • pad_inches (float) - amount of padding around the figure

Returns path of saved plot

Export

HiVis.save(path=None)[source]

Saves the instance in pickle format. If no path specified, will save in the path_output as the name of the instance.

Returns the path of the file (str)

HiVis.export_h5(path=None, force=False)[source]

Exports the adata as h5ad.

Parameters:
  • path (str) - path to save the h5 file. If None, will save to path_output

  • force (bool) - save file even if it already exists

Returns path where the file was saved (str)

HiVis.export_images(path=None, force=False)[source]

Exports full, high and low resolution images, and bins x,y coordinates, and the unit conversion json.

Parameters:
  • path (str) - path to save the image files. If None, will save to path_output

  • force (bool)- save files even if they already exists

Returns list of [3 images (np.array) and the spatial json]

Attributes

HiVis.adata

AnnData that stores the data and metadata of the bins

HiVis.agg

Dictionary that stores all Aggregation objects

HiVis.properties

Dictionary, can store any information

HiVis.shape

Returns adata.shape

HiVis.columns

Returns adata.columns

HiVis.name

Name of the object

HiVis.path_output

Path where all plots and files will be saved

HiVis.image_fullres

Fullres image. Also available highres and lowres.

HiVis.fluorescence

Dictionary, stores fluorescence information (channels and display colors)

HiVis.json

Dictionary, stores spatial scale factors

Aggregation

Stores the data and images of the aggregated VisiumHD bins, enables plotting via Aggregation.plot.

General methods

Aggregation.copy(new_name=None, new_out_path=False, full=False)[source]

Creates a deep copy of the instance if new_name is specified, renames the object and changes the path_output. If full is False, the name will be added to the current (previous) name.

Returns new Aggregation instance

Aggregation.rename(new_name: str, new_out_path=True, full=False)[source]

Renames the object and changes the path_output. If full is False, the name will be added to the current (previous) name

Aggregation.merge(adata, obs=None, var=None, layer=None, umap=True, pca=True, hvg=True, obsm=None, uns=None)[source]

Merge info from an anndata to self.adata, in case genes have been filtered.

Parameters:
  • adata (ad.AnnData) - anndata where to get the values from

  • obs - single string or list of obs to merge

  • var - single string or list of var to merge

  • layer - single string or list of layers to merge

  • umap (bool) - add umap to OBSM, and UMAP coordinates to obs

  • pca (bool) - add PCA to OBSM

  • hvg (bool) - add highly variable genes to vars

Aggregation.sync(what: str)[source]

Transfers metadata assignment from the Aggregation to the spots.

Parameters:
  • what (str) - obs column name to pass to HiViz object

Aggregation.combine(other)[source]

Combines two Aggregation objects into a single adata. Spatial plots and analysis will be disabled.

Aggregation.import_geometry(geojson_path, object_type='cell')[source]

Adds “geometry” column to self.adata.obs, based on Geojson exported from Qupath.

Parameters:
  • geojson_path (str) - path to geojson file (can also be a geodataframe)

  • object_type (str) - which “objectType” to merge from the geojson

Aggregation.head(n=5)[source]

Returns Aggregation.adata.obs.head(n), where n is number of rows

Aggregation.update()[source]

Updates the methods in the instance. Should be used after modifying the source code in the class

Analyses

Methods are called by Aggregation.analysis.

AnalysisAgg.dge(column, group1, group2=None, method='wilcox', two_sided=False, umi_thresh=0, inplace=False, layer=None)[source]

Runs differential gene expression analysis between two groups. Values will be saved in self.main.var: expression_mean, log2fc, pval

Parameters:
  • column (str) - which column in obs has the groups classification

  • group1 (str) - specific value in the “column”

  • group2 (str) - specific value in the “column”. if None, will run against all other values, and will be called “rest”

  • method (str) - one of [“fisher_exact”, “wilcox”, “t_test”]

  • two_sided (bool) - if one sided, will give the pval for each group, and the minimal of both groups (which will also be FDR adjusted)

  • umi_thresh (int) - use only spots with more UMIs than this number

  • inplace (bool) - modify the adata.var with log2fc, pval and expression columns

  • layer (str) - which layer in the AnnData to use

Returns the DGE results (pd.DataFrame)

AnalysisAgg.pseudobulk(by=None, layer=None, normalize=True)[source]

Sums the gene expression for each group in a single obs.

Parameters:
  • by (str) - return a dataframe, each column is a value in “by” (for example cluster), rows are genes. If None, will return the mean expression of every gene.

  • layer (str) - which layer in adata to use.

  • normalize (bool) - normalize the values to the sum of each group. if False, values will be the sum of each category.

Returns the gene expression for each group (pd.DataFrame)

AnalysisAgg.noise_mean_curve(layer=None, inplace=False, poly_deg=4)[source]

Generates a noise-mean curve of the data.

Parameters:
  • layer (str) - which layer in the AnnData to use

  • inplace (bool) - add the mean_expression, cv and residuals to VAR

  • poly_deg (int) - degree of polynomial fit. if 1, will be a linear model.

Returns dataframe with expression, CV and residuals of each gene (pd.DataFrame).

AnalysisAgg.cor(what, self_corr_value=None, normalize=True, layer: str = None, inplace=False)[source]

Calculates gene(s) correlation.

Parameters:
  • what (str or list) - if str, computes Spearman correlation of a given gene with all genes. if list, will compute correlation between all genes in the list

  • self_corr_value - replace the correlation of the gene with itself by this value

  • normalize (bool) - normalize expression before computing correlation

  • layer (str) - which layer in the AnnData to use

  • inplace (bool) - add the correlation to VAR

Returns dataframe of spearman correlation between genes (pd.DataFrame)

AnalysisAgg.score_genes(gene_list: list, score_name: str, z_normalize=False)[source]

Assigns score for each object, based on a list of genes.

Parameters:
  • gene_list (list) - list of genes

  • score_name (str) - name of column that will store the score in self.main.adata.obs

  • z_normalize (bool) - Z transform the score values

returns score values (pd.Series)

AnalysisAgg.smooth(what, radius, method='mean', new_col_name=None, layer=None, **kwargs)[source]

Applies median smoothing to the specified column in adata.obs using spatial neighbors.

Parameters:
  • what (str) - what to smooth. either a gene name or column name from self.main.adata.obs

  • radius (float) - in microns

  • method - [“mode”, “median”, “mean”, “gaussian”, “log”]

  • new_col_name (str) - Optional custom name for the output column

  • layer (str) - which layer in the AnnData to use

  • **kwargs - Additional Parameters for specific methods (e.g., sigma for gaussian, offset for log).

returns smoothed values (pd.Series)

AnalysisAgg.compute_distances(target_agg, dist_col_name=None, nearest_col_name=None)[source]

Compute distances of each object to the nearest object of another Aggregation.

Parameters:
  • target_agg - either Aggregation object, or a name (str) that is the key in self.main.viz.agg

  • dist_col_name (str) - Name of column to save distance to. default is dist_to_{agg_name}

  • nearest_col_name (str) - Name of column to save the closest aggregation name

Plots

Methods are called by Aggregation.plot.

PlotAgg.spatial(what=None, image=True, img_resolution=None, ax=None, title=None, cmap='winter', layer=None, legend=True, alpha=1, figsize=(7, 7), save=False, size=1, brightness=1, contrast=1, rasterize=False, xlim=None, ylim=None, scalebar=True, legend_title=None, axis_labels=False, show_zeros=False)[source]

Plot a spatial representation of self.adata.

Parameters:
  • what (str) - what to color the objects with (fill) - can be column from obs or a gene

  • image (bool) - plot the image underneath the objects

  • img_resolution - which resolution to use for the image - can be “full”,”high”,”low”

  • brightness, contrast - for image modification

  • cmap - can be string (name of pellate), list of colors, or in categorical values case, a dict {“value”:”color”}

  • xlim, ylim - two values each, in microns. example: xlim=[50,100]

  • scalebar - either the length in microns (or None for 0.2 of xlim length), or False to not show the scalebar, or a dict with arguments for add_scalebar(), such as:

    {length_microns=None, text=True, line_width=4, color=’white’, text_offset=0.035}

  • save (bool) - save the plot

  • layer (str) - which layer in adata to use

  • ax (optional) - matplotlib ax, if not passed, new figure will be created with size=figsize

  • brightness (float) - increases brigtness, for example 0.2.

  • contrast (float) - > 1 increases contrast, < 1 decreases.

  • figsize, legend, alpha, title, legend_title, axis_labels - cosmetic Parameters

  • rasterize - Rasterize elements for smaller figure size

Returns ax

PlotAgg.cells(what=None, image=True, img_resolution=None, xlim=None, ylim=None, scalebar=True, show_zeros=False, figsize=(7, 7), line_color='black', cmap='viridis', alpha=0.7, linewidth=1, save=False, layer=None, legend=True, ax=None, title=None, legend_title=None, brightness=1, contrast=1, axis_labels=False, rasterize=False)[source]

Plot a spatial map of the objects. Can color the borders and fill

Parameters:
  • what (str) - what to color the objects with (fill) - can be column from obs or a gene

  • image (bool) - plot the image underneath the objects

  • img_resolution - which resolution to use for the image - can be “full”,”high”,”low”

  • brightness, contrast - for image modification

  • cmap - can be string (name of pellate), list of colors, or in categorical values case, a dict {“value”:”color”}

  • xlim, ylim - two values each, in microns [50,100]

  • scalebar - either the length in microns (or None for 0.2 of xlim length), or False to not show the scalebar, or a dict with arguments for add_scalebar(), such as:

    {length_microns=None, text=True, line_width=4, color=’white’, text_offset=0.035}

  • ax (optional) - matplotlib ax, if not passed, new figure will be created with size=figsize

  • layer (str) - which layer in adata to use.

  • save (bool) - svae the plot

  • brightness (float) - increases brigtness, for example 0.2.

  • contrast (float) - > 1 increases contrast, < 1 decreases.

  • figsize, line_color, color_zeros, legend, linewidth, title, legend_title, axis_labels - cosmetic Parameters

Returns ax

PlotAgg.umap(features=None, basis='X_umap', title=None, size=None, layer=None, legend=True, texts=False, vmax=None, legend_loc='right margin', save=False, ax=None, figsize=(7, 7), cmap='viridis', axis_labels=True, rasterize=True)[source]

Plot a UMAP of self.adata, if present

Parameters:
  • features - if None, won’t color. can be a string or list of strings, passed to scanpy.pl.umap

  • basis - passed to sc.pl.embedding. where from obsm take the results

  • layer (str) - which layer to use from the self.adata. If None, will use X

  • texts (bool) - add text in the center of mass of categorical case

  • cmap - can be string (name of pellate), list of colors, or in categorical values case, a dict {“value”:”color”}

  • ax (optional) - matplotlib ax, if not passed, new figure will be created with size=figsize

  • figsize, size, legend, legend_loc, title, legend_title, axis_labels - cosmetic Parameters

  • save (bool) - svae the plot

  • rasterize - Rasterize elements for smaller figure size

Returns ax

PlotAgg.hist(what, bins=20, xlim=None, title=None, ylab=None, xlab=None, ax=None, layer=None, save=False, figsize=(7, 7), cmap=None, color='blue', cropped=False)[source]

Plots histogram of data or metadata. if categorical, will plot barplot

Parameters:
  • what (str) - what to plot. can be metadata (obs/var colnames or a gene)

  • bins (int) - number of bins of the histogram

  • ax (optional) - matplotlib ax, if not passed, new figure will be created with size=figsize

  • cmap - colorbar to use. Can be string, list of colors, or dictionary of {val:color}. overrides the color argument for barplot

  • color (str) - color of the histogram

  • layer (str) - which layer in adata to use

  • title, xlab, ylab - strings

  • save (bool) - save the plot

  • xlim (list) - two values, where to crop the x axis. example [50,100]

Returns ax

PlotAgg.cor(what, number_of_genes=10, normalize=True, self_corr_value=numpy.nan, layer=None, cluster=True, ax=None, figsize=(7, 7), save=False, size=15, text=True, cmap='copper', legend=True, legend_title=None, print_=False)[source]

Plots correlation of a gene with all genes, or a correlation matrix between list of genes.

Parameters:
  • what - either a str or a list. if a single genes, will plot correlation to all other genes. in this case, will pull and save the data to Aggregation.adata.var. if a list of genes, will plot a heatmap.

  • number_of_genes (int) - only applicable if what is a single gene. how many gene names (text) to add to the plot.

  • cluster (bool) - only applicable if what is a list of genes. whether to cluster the heatmap

  • normalize (bool) - normalize data before performing correlation.

  • layer (str)- which layer to use from the self.adata. If None, will use X

  • ax (optional) - matplotlib ax, if not passed, new figure will be created with size=figsize

  • cmap - colormap for scatterplot / heatmap. in heatmap can be list of colors.

  • size (int) - size of spots in scatterplot.

  • save (bool) - svae the plot

  • text, legend, legend_title - cosmetic Parameters

  • print_ (bool) - print most correlated genes

Returns ax

PlotAgg.noise_mean_curve(poly_deg=4, signif_thresh=0.999, layer=None, save=False, ax=None, text=True, figsize=(7, 7), color='black', size=10, cmap='cool', repel=False, title=None, legend=True, fit_color=None)[source]

Generates a noise-mean curve of the data.

Parameters:
  • poly_deg (int > 0) - degree of polynomial to fit the data.

  • signif_thresh (float) - add text for genes in this residual percentile

  • layer (str) - which layer in the AnnData to use

  • ax (optional) - matplotlib ax, if not passed, new figure will be created with size=figsize

  • cmap - colormap for scatterplot. can be name of colormap, or list of colors

  • size (int) - size of dots in scatterplot

  • save (bool) - svae the plot

  • repel (bool) - repel text

  • fit_color (str) - color to plot the fitted curve

  • title, color, legend - cosmetic parameters

returns ax

PlotAgg.save(figname: str, fig=None, ax=None, open_file=False, formats=['pdf', 'svg', 'png'], dpi=300, pad_inches=0)[source]

Saves a figure or ax. If no fig or ax are specified, will save the last plot.

Parameters:
  • figname (str) - name of plot

  • fig (optional) - plt.Figure object to save, can be a dataframe for writing csv.

  • ax - ax to save. if not passed, will use self.current_ax

  • open_file (bool) - open the file after saving

  • formats (str or list) - format(s) of file to save

  • dpi (int) - resolution in dot per inch

  • pad_inches (float) - amount of padding around the figure

Returns path of daved file

Export

Aggregation.export_h5(path=None)[source]

Exports the adata.

Parameters:
  • path (str) - path to save the h5 file. If None, will save to path_output

Returns path where the file was saved (str)

Aggregation.export_to_matlab(path=None, layer=None)[source]

Exports gene names, data (sparse matrix) and metadata to a .mat file.

Parameters:
  • path (str) - path of mat file to save to

  • layer - which layer from the adata to use

Returns path of mat file

Attributes

Aggregation.adata

AnnData that stores the data and metadata of the objects

Aggregation.viz

HiVis parent object that is linked to this instance

Aggregation.shape

Returns adata.shape

Aggregation.columns

Returns adata.columns

Aggregation.name

Name of the object

Aggregation.path_output

Path where all plots and files will be saved