Plotting¶
Plot cell abundance for multiple cell types using colour interpolation¶
-
cell2location.plt.
plot_spatial
(adata, color, img_key='hires', show_img=True, **kwargs)[source]¶ Plot spatial abundance of cell types (regulatory programmes) with colour gradient and interpolation (from Visium anndata).
This method supports only 7 cell types with these colours (in order, which can be changed using reorder_cmap). ‘yellow’ ‘orange’ ‘blue’ ‘green’ ‘purple’ ‘grey’ ‘white’
- Parameters
adata – adata object with spatial coordinates in adata.obsm[‘spatial’]
color – list of adata.obs column names to be plotted
kwargs – arguments to plot_spatial_general
- Returns
matplotlib figure
-
cell2location.plt.plot_spatial.
plot_spatial_general
(value_df, coords, labels, text=None, circle_diameter=4.0, alpha_scaling=1.0, max_col=inf, inf, inf, inf, inf, inf, inf, max_color_quantile=0.98, show_img=True, img=None, img_alpha=1.0, adjust_text=False, plt_axis='off', axis_y_flipped=True, x_y_labels='', '', crop_x=None, crop_y=None, text_box_alpha=0.9, reorder_cmap=range(0, 7), style='fast', colorbar_position='bottom', colorbar_label_kw={}, colorbar_shape={}, colorbar_tick_size=12, colorbar_grid=None, image_cmap='Greys_r', white_spacing=20)[source]¶ Plot spatial abundance of cell types (regulatory programmes) with colour gradient and interpolation.
This method supports only 7 cell types with these colours (in order, which can be changed using reorder_cmap). ‘yellow’ ‘orange’ ‘blue’ ‘green’ ‘purple’ ‘grey’ ‘white’
- Parameters
value_df – pd.DataFrame - with cell abundance or other features (only 7 allowed, columns) across locations (rows)
coords – np.ndarray - x and y coordinates (in columns) to be used for ploting spots
text – pd.DataFrame - with x, y coordinates, text to be printed
circle_diameter – diameter of circles
labels – list of strings, labels of cell types
alpha_scaling – adjust color alpha
max_col – crops the colorscale maximum value for each column in value_df.
max_color_quantile – crops the colorscale at x quantile of the data.
show_img – show image?
img – numpy array representing a tissue image. If not provided a black background image is used.
img_alpha – transparency of the image
lim – x and y max limits on the plot. Minimum is always set to 0, if lim is None maximum is set to image height and width. If ‘no_limit’ then no limit is set.
adjust_text – move text label to prevent overlap
plt_axis – show axes?
axis_y_flipped – flip y axis to match coordinates of the plotted image
reorder_cmap – reorder colors to make sure you get the right color for each category
style – plot style (matplolib.style.context): ‘fast’ - white background & dark text; ‘dark_background’ - black background & white text;
colorbar_position – ‘bottom’, ‘right’ or None
colorbar_label_kw – dict that will be forwarded to ax.set_label()
colorbar_shape – dict {‘vertical_gaps’: 1.5, ‘horizontal_gaps’: 1.5, ‘width’: 0.2, ‘height’: 0.2}, not obligatory to contain all params
colorbar_tick_size – colorbar ticks label size
colorbar_grid – tuple of colorbar grid (rows, columns)
image_cmap – matplotlib colormap for grayscale image
white_spacing – percent of colorbars to be hidden
Plot heatmap and dotplot (hierarchically clustered but without showing the tree)¶
-
cell2location.plt.plot_heatmap.
heatmap
(array, ticks=False, log=False, figsize=None, equal=False, row_labels=None, col_labels=None, cbar=True, cmap='RdPu', title='', vmin=None, vmax=None)[source]¶ Plot heatmap with row and column labels using plt.imshow
- Parameters
array – np.ndarray to be visualised, or an object that can be coerced to np.ndarray
ticks – boolean, show x and y axis ticks?
log – boolean, color on logscale?
figsize – figure size as a tuple (x, y)
equal – boolean, each tile should be square (equal aspect)
row_labels – names of rows (pd.Series, pd.Index or list)
col_labels – names of columns (pd.Series, pd.Index or list)
cbar – boolean, show colorbar?
cmap – valid matplotlib colormap name
title – title of the plot
-
cell2location.plt.plot_heatmap.
dotplot
(array_color, array_size=None, ticks=False, log=False, figsize=None, equal=False, row_labels=None, col_labels=None, cbar=True, cmap='RdPu', title='')[source]¶ Plot dotplot with row and column labels
- Parameters
array_color – np.ndarray to be visualised as dot color
array_size – np.ndarray to be visualised as dor size
ticks – boolean, show x and y axis ticks?
log – boolean, color on logscale?
figsize – figure size as a tuple (x, y)
equal – boolean, each tile should be square (equal aspect)
row_labels – names of rows (pd.Series, pd.Index or list)
col_labels – names of columns (pd.Series, pd.Index or list)
cbar – boolean, show colorbar?
cmap – valid matplotlib colormap name
title – title of the plot
-
cell2location.plt.plot_heatmap.
clustermap
(df, cluster_rows=True, cluster_cols=True, figure_size=5, 5, cmap='RdPu', log=False, return_linkage=False, equal=True, title='', fun_type='heatmap', array_size=None, vmin=None, vmax=None)[source]¶ Plot heatmap with hierarchically clustered rows and columns using cell2location.plt.plot_heatmap.heatmap() and cell2location.plt.plot_heatmap.dotplot().
- Parameters
df – pandas.DataFrame to be visualised using heatmap and dotplot
cluster_rows – cluster rows or keep the same order as df?
cluster_cols – cluster columns or keep the same order as df?
figure_size – tuple specifying figure dimensions, passed to .heatmap
cmap – pyplot colormap, passed to .heatmap
log – boolean, color on logscale?
return_linkage – return the plot or the plot + linkage for rows and columns? If true returns a dictionary with ‘plot’, ‘row_linkage’ and ‘col_linkage’ elements.
equal – boolean, each tile should be square (equal aspect)
title – clustermap title
fun_type – ‘heatmap’ or ‘dotplot’
array_size – pandas.DataFrame to be visualised as dotplot dot size - must have the same dimensions as df (Default None)
Other plotting functions¶
Rotate and crop image and location coordinates¶
Class for rotating and cropping images.
-
cell2location.plt.RotateCrop.
find_rectangle_corners
(bottom_left, width)[source]¶ Find rectangle corners given positions of left side points and width of the plot.
- Parameters
bottom_left – array with x/y positions (columns) of top left and bottom left corners (in rows).
width – width of the rectangle.
Video illustrating mapping¶
-
cell2location.plt.mapping_video.
interpolate_coord
(start=10, end=5, steps=100, accel_power=3, accelerate=True, jitter=None)[source]¶ Interpolate coordinates between start_array and end_array positions in N steps with non-linearity in movement according to acc_power, and accelerate change in coordinates (True) or slow it down (False).
- Parameters
jitter – shift positions by a random number by sampling: new_coord = np.random.normal(mean=coord, sd=jitter), reasonable values 0.01-0.1
-
cell2location.plt.mapping_video.
plot_video_mapping
(adata_vis, adata, sample_ids, spot_factors_df, sel_clust, sel_clust_col, sample_id, sc_img=None, sp_img=None, sp_img_scaling_fac=1, adata_cluster_col='annotation_1', cell_fact_df=None, step_n=[20, 100, 15, 45, 80, 30], step_quantile=[1, 1, 1, 1, 0.95, 0.95], sc_point_size=1, aver_point_size=20, sp_point_size=5, reorder_cmap=range(0, 7), label_clusters=False, style='dark_background', adjust_text=False, sc_alpha=0.6, sp_alpha=0.8, img_alpha=0.8, sc_power=20, sp_power=20, sc_accel_power=3, sp_accel_power=3, sc_accel_decel=True, sp_accel_decel=False, sc_jitter=None, sp_jitter=None, save_path='./results/mouse_viseum_snrna/std_model/mapping_video/', crop_x=None, crop_y=None, save_extension='png', colorbar_shape={'horizontal_gaps': 0.13, 'vertical_gaps': 2})[source]¶ Create frames for a video illustrating the approach from UMAP of single cells to their spatial locations. We use linear interpolation of UMAP and spot coordinates to create movement.
- Parameters
adata_vis – anndata with Visium data (including spatial slot in .obsm)
adata – anndata with single cell data (including X_umap slot in .obsm)
sample_ids – pd.Series - sample ID for each spot
spot_factors_df – output of the model showing spatial expression of cell types / factors.
sel_clust – selected cluster names in adata_cluster_col column of adata.obs
sel_clust_col – selected cluster column name in spot_factors_df
sample_id – sample id to use for visualisation
adata_cluster_col – column in adata.obs containing cluster annotations
cell_fact_df – alternative to adata_cluster_col, pd.DataFrame specifying class for each cell (can be continuous).
step_n – how many frames to record in each step: UMAP, UMAP collapsing into averages, averages, averages expanding into locations, locations.
step_quantile – how to choose maximum colorscale limit in each step? (quantile) Use 1 for discrete values.
sc_point_size – point size for cells
aver_point_size – point size for averages
sp_point_size – point size for spots
fontsize – size of text label of averages
adjust_text – adjust text label position to avoid overlaps
sp_alpha (sc_alpha,) – color alpha scaling for single cells and spatial.
sp_power (sc_power,) – change dot size nonlinearly with this exponent
sp_accel_power (sc_accel_power,) – change movement speed size nonlinearly with this exponent
sp_accel_decel (sc_accel_decel,) – accelerate (True) or decelereate (False)
save_path – path where to save frames (named according to order of steps)
Expected vs Observed model result QC plot¶
-
cell2location.plt.plot_expected_vs_obs.
plot_expected_vs_obs
(mu, data, gene1='ENSG00000081237', gene1_lab='PTPRC', gene2='ENSG00000167286', gene2_lab='CD3D')[source]¶ Plot expected vs observed values of a pair of genes (2D histogram).
- Parameters
mu – ndarray of values expected by the model
data – anndata object containing observed data
gene1 – gene 1 in anndata.varnames
gene1_lab – gene names to show on the plot
gene2 – gene 2 in anndata.varnames
gene2_lab – gene names to show on the plot
Plot factor spatial (legacy, now using scanpy.pl.spatial)¶
-
cell2location.plt.plot_factor_spatial.
plot_factor_spatial
(adata, fact, cluster_names, fact_ind=[0], trans='log', sample_name=None, samples_col='sample', obs_x='imagecol', obs_y='imagerow', n_columns=6, max_col=5000, col_breaks=[0.1, 100, 1000, 3000], figure_size=24, 5.7, point_size=0.8, text_size=9)[source]¶ Plot expression of factors / cell types in space. Convenient but not as powerful as scanpy plotting.
- Parameters
adata – anndata object with spatial data
fact – pd.DataFrame with spatial expression of factors (W), e.g. mod.spot_factors_df
cluster_names – names of those factors to show on a plot
fact_ind – index of factors to plot
trans – transform colorscale? passed to plotnine.scale_color_cmap
sample_name – if anndata object contains multiple samples specify which sample to plot (no warning given if not)
samples_col – if anndata object contains multiple which .obs columns specifies sample?
obs_x – which .obs columns specifies x coordinate?
obs_y – which .obs columns specifies y coordinate?
n_columns – how many factors / clusters to plot in each row (plotnine.facet_grid)
max_col – colorscale maximum expression in fact
col_breaks – colorscale breaks
figure_size – figures size works weirdly (only x axis has an effect, use 24 for 6-column plot, 12 for 3, 8 for 2 …).
point_size – point size of spots
text_size – text size
Module contents¶
-
cell2location.plt.
plot_density_1D
(adata_sp, subset=None, saving=False, scaling=0.15, power=1, pws=[0, 0, 100, 500, 1000, 3000, 6000, 10000], dimName='VCDepth', areaName='AOISurfaceArea', xlab='Cortical Depth', colourCode=None, figureSize=12, 8)[source]¶ Plot density of celltypes in a dotplot across 1 dimension
- Parameters
adata_sp – anndata object for spatial data with celltype abundance included in .obs (this is returned by running cell2location first)
subset – optionally a boolean for only using part of the data in adata_sp
saving – optionally a string value, which will result in the plot to be saved under this name
scaling – how dot size should scale linearly with abundance values, default 0.15
power – how dot size should scale non-linearly with abundance values, default 1 (no non-linear scaling)
pws – which abundance values to show in the legend
dimName – the name of the column in adata_sp.obs that contains the dimension used for plotting
areaName – the name of the column in adata_sp.obs that contain the area of each ROI (assumed to be square micrometer)
xlab – the x-axis label for the plot
colourCode – optionally a dictionary mapping cell type names to colours
figureSize – size of the figure
-
cell2location.plt.
plot_absolute_abundances_1D
(adata_sp, roi_subset=False, saving=False, celltype_subset=False, scaling=0.15, power=1, pws=[0, 0, 100, 500, 1000, 3000, 6000], dimName='VCDepth', xlab='Cortical Depth', colourCode=None, figureSize=12, 8)[source]¶ Plot absolute abundance of celltypes in a dotplot across 1 dimension
- Parameters
adata_sp – anndata object for spatial data with celltype abundance included in .obs (this is returned by running cell2location first)
celltype_subset – list of a subset of cell type names to be plotted
slide&radial_position – if wanting to plot only data from one slide + one radial position, include in these parameters
cell_types – parameter for only plotting specific cell types where column names in adata_sp.obs are meanSpot[celltype] format
roi_subset – optionally a boolean for only using part of the data in adata_sp (corresponding to a specific ROI)
saving – optionally a string value, which will result in the plot to be saved under this name
scaling – how dot size should scale linearly with abundance values, default 0.15
power – how dot size should scale non-linearly with abundance values, default 1 (no non-linear scaling)
pws – which abundance values to show in the legend
dimName – the name of the dimensions in adata_sp.obs to use for plotting
xlab – the x-axis label for the plot
colourCode – optionally a dictionary mapping cell type names to colours
figureSize – size of the figure