# Developing-Heart-Local-Improved - Xenium Analysis

**Pages:** 3

---

## Notebook

**URL:** http://127.0.0.1:9020/notebooks_html/Fig2_Overview_of_cellular_niches_and_TissueTypist/tissuetypist_assess_Xenium5000.html

**Contents:**
- Import modules¶
- Read in qeury adata¶
- Read in reference adata¶
- Harmonise cell type names¶
- Calculate cell type proportions per niche¶
  - Query¶
  - Reference¶
- Subset shared cell types¶

**Examples:**

Example 1 (python):
```python
import numpy as np
import pandas as pd
import scanpy as sc
import anndata
import os
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib as mpl
# enables correct plotting of text
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['ps.fonttype'] = 42 

sc.settings.verbosity = 1  # verbosity: errors (0), warnings (1), info (2), hints (3)
```

Example 2 (python):
```python
import importlib.util
import sys
spec = importlib.util.spec_from_file_location("module.name", "/nfs/team205/kk18/function/python/utils.py")
utils = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = utils
spec.loader.exec_module(utils)
```

Example 3 (unknown):
```unknown
figdir = '/nfs/team205/heart/fetal_ms_figures/raw_plots_kk/Aug2024'
table_dir = '/nfs/team205/heart/fetal_ms_figures/tables/Aug2024'
```

Example 4 (python):
```python
# read in 
celltype_col = 'fine_grain_4Jan2025'
path_to_adata = '/lustre/scratch126/cellgen/team205/kk18/xenium/objects/foetal/C194-HEA-0-FFPE-1_Hst45-HEA-0-FFPE-1_concat_5K_filtered_raw.h5ad'
adata = sc.read_h5ad(path_to_adata)
print(adata.X.data[:5])
adata
```

Example 5 (unknown):
```unknown
[5. 1. 1. 2. 2.]
```

Example 6 (unknown):
```unknown
AnnData object with n_obs × n_vars = 362277 × 5001
    obs: 'cell_id', 'x_centroid', 'y_centroid', 'transcript_counts', 'control_probe_counts', 'genomic_control_counts', 'control_codeword_counts', 'unassigned_codeword_counts', 'deprecated_codeword_counts', 'total_counts', 'cell_area', 'nucleus_area', 'nucleus_count', 'segmentation_method', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'log1p_total_counts', 'pct_counts_in_top_10_genes', 'pct_counts_in_top_20_genes', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_150_genes', 'n_counts', 'n_genes', 'tissue_block_id', 'celltypist_coarse', 'conf_score_coarse', 'celltypist_coarse_fin', 'celltypist_coarse2midmod', 'conf_score_coarse2midmod', 'celltypist_mid_fin', 'celltypist_midmod2fine', 'conf_score_midmod2fine', 'fine_grain_8Dec2024', 'multi_celltypes_coarse', 'cluster_cellcharter', 'fine_grain_4Jan2025', 'sliding_window_assignment', 'globalX', 'globalY', 'predicted_labels_sliding_window_assignment', 'conf_score_sliding_window_assignment', 'window_col', 'window_row', 'tt_prediction', 'tt_prediction_mod'
    var: 'gene_ids', 'feature_types', 'genome', 'n_cells_by_counts-0', 'mean_counts-0', 'log1p_mean_counts-0', 'pct_dropout_by_counts-0', 'total_counts-0', 'log1p_total_counts-0', 'n_cells_by_counts-1', 'mean_counts-1', 'log1p_mean_counts-1', 'pct_dropout_by_counts-1', 'total_counts-1', 'log1p_total_counts-1'
    uns: 'celltypist_mid_fin_colors', 'fine_grain_4Jan2025_colors', 'fine_grain_8Dec2024_colors', 'multi_celltypes_coarse_colors', 'pca', 'pca_harmony', 'spatial_neighbors', 'tissue_block_id_colors', 'umap'
    obsm: 'X_cellcharter', 'X_pca', 'X_pca_harmony', 'X_umap_pca', 'X_umap_pca_harmony', 'spatial'
    varm: 'PCs'
    obsp: 'pca_harmony_connectivities', 'pca_harmony_distances', 'spatial_connectivities', 'spatial_distances'
```

Example 7 (python):
```python
# update cell type name for plotting
df = pd.read_csv('/nfs/team205/heart/anndata_objects/Foetal/finegrain_name_mapping.csv')
celltype_mapping = df.set_index('Full_name')['Short_name_finalised'].to_dict()
adata.obs.replace({celltype_col:celltype_mapping},inplace=True)
```

Example 8 (python):
```python
/tmp/ipykernel_3792320/1210424873.py:4: FutureWarning: The behavior of Series.replace (and DataFrame.replace) with CategoricalDtype is deprecated. In a future version, replace will only be used for cases that preserve the categories. To change the categories, use ser.cat.rename_categories instead.
  adata.obs.replace({celltype_col:celltype_mapping},inplace=True)
```

Example 9 (python):
```python
adata_ref = sc.read_h5ad('/nfs/team205/heart/anndata_objects/Foetal/visium_foetal_healthy-all_cell2loc-adata.h5ad')
adata_ref
```

Example 10 (unknown):
```unknown
AnnData object with n_obs × n_vars = 39223 × 58
    obs: 'array_row', 'array_col', 'sample', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_100_genes', 'pct_counts_in_top_200_genes', 'pct_counts_in_top_500_genes', 'mt_frac', 'sangerID', 'Publication', 'combinedID', 'donor', 'donor_type', 'region', 'region_finest', 'age', 'gender', 'facility', 'cell_or_nuclei', 'modality', 'kit_10x', 'flushed', 'status', 'cell2loc-map_group', 'JC_edit', 'sample_for_cell2loc', 'week', 'leiden', 'annotation_final', 'annotation_final_mod'
    uns: 'JC_edit_colors', 'annotation_colors', 'annotation_final_colors', 'cell2loc-map_group_colors', 'leiden', 'neighbors', 'region_cluster_colors', 'sample_for_cell2loc_colors', 'umap'
    obsm: 'MT', 'X_umap', 'means_cell_abundance_w_sf', 'q05_cell_abundance_w_sf', 'q05_cell_abundance_w_sf_ndarray', 'q95_cell_abundance_w_sf', 'spatial', 'stds_cell_abundance_w_sf'
    obsp: 'connectivities', 'distances'
```

Example 11 (python):
```python
# update cell type name
df = pd.read_csv('/nfs/team205/heart/anndata_objects/Foetal/finegrain_name_mapping.csv')
celltype_mapping = df.set_index('Full_name')['Short_name_finalised'].to_dict()
adata_ref.var_names = [celltype_mapping[x] for x in adata_ref.var_names]
```

Example 12 (python):
```python
celltype_mapping_2 = {
    'BMS4':'B',
    'CorAdvFB':'FB',
    'GVAdvFB':'FB',
    'MonoMPO':'Mono',
    'MyoFB':'FB',
    'MyoFb':'FB',
     'ProB':'B',
    'SubEpiFb':'FB',
    'vCMCL':'vCM',
    'vCMCR':'vCM',
    'vCMTL':'vCM',
    'vCMTR':'vCM',
    'FBCOL2A1':'FB',
    'GVSMCP':'GVSMC',
    'GVSMCT':'GVSMC',
    'SANPCHd':'SANPC',
     'SANPCHn':'SANPC',
     'SANPCT':'SANPC',
    'CorCapECN':'CorCapEC',
    'DCMat':'DC',
 'DCT1':'DC',
}
adata.obs[celltype_col] = [celltype_mapping_2[x] if x in celltype_mapping_2.keys() else x for x in adata.obs[celltype_col]]
adata_ref.var_names = [celltype_mapping_2[x] if x in celltype_mapping_2.keys() else x for x in adata_ref.var_names]
```

Example 13 (python):
```python
set(adata_ref.var_names) - set(adata.obs[celltype_col])
```

Example 14 (unknown):
```unknown
{'LNFRC',
 'MPATF3',
 'MPTIMD4',
 'MoDC',
 'NK',
 'Treg',
 'VCSProx',
 'ValveIC',
 'pDC'}
```

Example 15 (python):
```python
set(adata.obs[celltype_col]) - set(adata_ref.var_names)
```

Example 16 (unknown):
```unknown
{'?EpendymalCells',
 '?EpithelialCells',
 '?SkeletalMuscle',
 '?ThyroidCells',
 'AtrialCardiomyocytes_DoubletWithEC',
 'AtrialCardiomyocytes_DoubletWithFB',
 'CorCapECCyc',
 'CoronaryCapillaryEndothelialCells_DoubletsWithEryth',
 'ELNeuro',
 'EndocardCyc',
 'EndocardialCells_Doublets',
 'Eryth',
 'ErythCyc',
 'FBCyc',
 'GVSMCCyc',
 'MyeloidCells_Doublets',
 'PericCyc',
 'PericFib',
 'PericInt',
 'SOX2_LAMB3_pos',
 'SchwCyc',
 'SchwNeuro',
 'ThyroidEpithelialCells',
 'aCMCyc',
 'doublets',
 'unassigned',
 'unclassified',
 'vCMCyc'}
```

Example 17 (python):
```python
ctab = pd.crosstab(adata.obs[celltype_col],adata.obs['tt_prediction'])
prop_df = (ctab/ctab.sum(axis=0))
prop_df.sum(axis=0)
```

Example 18 (unknown):
```unknown
tt_prediction
AV ring                      1.0
AVnode                       1.0
Adventitia - GV              1.0
Atrium                       1.0
Coronary vessel              1.0
Ductus arteriosus            1.0
Endocardial cusion           1.0
Endocardium - Atrial         1.0
Endocardium - Ventricular    1.0
Epicardium                   1.0
Great vessel                 1.0
SAnode                       1.0
VCS - Distal                 1.0
VCS - Proximal               1.0
Valves                       1.0
Ventricle - Compact          1.0
Ventricle - Trabeculated     1.0
dtype: float64
```

Example 19 (unknown):
```unknown
prop_df.head()
```

Example 20 (python):
```python
df = adata_ref.to_df()
df['annotation_final_mod'] = adata_ref.obs['annotation_final_mod'].copy()
df = df.groupby('annotation_final_mod').sum()
df = df.groupby(df.columns, axis=1).sum()

prop_df_ref = (df.T/df.sum(axis=1))
prop_df_ref.sum(axis=0)
```

Example 21 (unknown):
```unknown
/tmp/ipykernel_3792320/4260203183.py:3: FutureWarning: The default of observed=False is deprecated and will be changed to True in a future version of pandas. Pass observed=False to retain current behavior or observed=True to adopt the future default and silence this warning.
  df = df.groupby('annotation_final_mod').sum()
/tmp/ipykernel_3792320/4260203183.py:4: FutureWarning: DataFrame.groupby with axis=1 is deprecated. Do `frame.T.groupby(...)` without axis instead.
  df = df.groupby(df.columns, axis=1).sum()
```

Example 22 (unknown):
```unknown
annotation_final_mod
Atrium                       1.0
Ventricle - Compact          1.0
Ventricle - Trabeculated     1.0
SAnode                       1.0
AVnode                       1.0
VCS - Proximal               1.0
VCS - Distal                 1.0
Great vessel                 1.0
Coronary vessel              1.0
Ductus arteriosus            1.0
Adventitia - Coronary        1.0
Adventitia - GV              1.0
Epicardium                   1.0
Endocardium - Atrial         1.0
Endocardium - Ventricular    1.0
Endocardial cusion           1.0
AV ring                      1.0
Valves                       1.0
LN                           1.0
dtype: float64
```

Example 23 (unknown):
```unknown
prop_df_ref.head()
```

Example 24 (python):
```python
# shared cell types
shared = [x for x in prop_df.index if x in prop_df_ref.index]
print(len(shared))
prop_df = prop_df.loc[shared]
prop_df_ref = prop_df_ref.loc[shared]
```

Example 25 (python):
```python
# shared niches
shared = [x for x in prop_df.columns if x in prop_df_ref.columns]
print(len(shared))
prop_df = prop_df[shared]
prop_df_ref = prop_df_ref[shared]
```

Example 26 (python):
```python
print(prop_df.shape)
print(prop_df_ref.shape)
```

Example 27 (unknown):
```unknown
(38, 17)
(38, 17)
```

Example 28 (python):
```python
%%time
corr, pval = utils.df_pearson_corr_with_p_vectorized(prop_df, prop_df_ref, p_adjust='fdr_bh')

# draw the initial clustermap (for ordering only)
cg = sns.clustermap(
    corr,
    cmap='vlag',
    center=0,
    metric='euclidean',
    method='average',
    figsize=(6, 6)
)

# 4) extract the leaf order and reindex both matrices
order = cg.dendrogram_row.reordered_ind
labels = list(corr.index[order])

corr_ord = corr.loc[labels, labels]
pval_ord = pval.loc[labels, labels]

# 5) replot as a heatmap and annotate significance
fig, ax = plt.subplots(figsize=(6, 6))
sns.heatmap(
    corr_ord,
    cmap='vlag',
    center=0,
    square=True,
    cbar_kws={'label': 'Pearson r'},
    ax=ax
)

# add asterisks for p < 0.01
n = corr_ord.shape[0]
for i in range(n):
    for j in range(n):
        if pval_ord.iat[i, j] < 0.01:
            ax.text(j + 0.5, i + 0.5, '*',
                    ha='center', va='center',
                    fontsize=10)

ax.set_xticklabels(labels, rotation=90)
ax.set_xlabel('Reference')
ax.set_yticklabels(labels, rotation=0)
ax.set_ylabel('Xenium-5K, TissueTypist prediction')
plt.tight_layout()
plt.savefig(f'{figdir}/TissueTypist_celltype-prop-corr_Xenium5K.pdf', bbox_inches="tight",dpi=300)
plt.show()
```

Example 29 (unknown):
```unknown
CPU times: user 1.23 s, sys: 69 ms, total: 1.3 s
Wall time: 1.37 s
```

---

## Notebook

**URL:** http://127.0.0.1:9020/notebooks_html/Fig1_General_processing/Xenium/plotting_for-Fig.html

**Contents:**
- Read in adata¶
- Log-normalisation¶
- Plot cell types¶
- UMAP¶
- TissueTypist niches¶

**Examples:**

Example 1 (python):
```python
import matplotlib.pyplot as plt
import scanpy as sc
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os

import matplotlib as mpl
# enables correct plotting of text
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['ps.fonttype'] = 42
```

Example 2 (python):
```python
sc.settings.set_figure_params(dpi=80)
```

Example 3 (unknown):
```unknown
os.getcwd()
```

Example 4 (unknown):
```unknown
'/rfs/project/rfs-iCNyzSAaucw/kk837/notebooks/Foetal/Xenium/5K/C194_Hst45/CamU'
```

Example 5 (unknown):
```unknown
figdir = '/rfs/project/rfs-iCNyzSAaucw/kk837/notebooks/Foetal/fetal_ms_figures'
# table_dir = '/nfs/team205/heart/fetal_ms_figures/tables/Aug2024'
```

Example 6 (unknown):
```unknown
celltype_key = 'fine_grain_12Jun2025'
```

Example 7 (python):
```python
objects_dir = '/home/kk837/rds/rds-teichlab-C9woKbOCf2Y/kk837/Foetal/anndata_objects/Xenium'
path_adata = f'{objects_dir}/C194-HEA-0-FFPE-1_Hst45-HEA-0-FFPE-1_concat_5K_filtered_raw.h5ad'
adata = sc.read_h5ad(path_adata)
adata
```

Example 8 (unknown):
```unknown
AnnData object with n_obs × n_vars = 362277 × 5001
    obs: 'cell_id', 'x_centroid', 'y_centroid', 'transcript_counts', 'control_probe_counts', 'genomic_control_counts', 'control_codeword_counts', 'unassigned_codeword_counts', 'deprecated_codeword_counts', 'total_counts', 'cell_area', 'nucleus_area', 'nucleus_count', 'segmentation_method', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'log1p_total_counts', 'pct_counts_in_top_10_genes', 'pct_counts_in_top_20_genes', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_150_genes', 'n_counts', 'n_genes', 'tissue_block_id', 'celltypist_coarse', 'conf_score_coarse', 'celltypist_coarse_fin', 'celltypist_coarse2midmod', 'conf_score_coarse2midmod', 'celltypist_mid_fin', 'celltypist_midmod2fine', 'conf_score_midmod2fine', 'pca_harmony_leiden_0.2', 'pca_harmony_leiden_0.3', 'pca_harmony_leiden_0.4', 'pca_harmony_leiden_0.5', 'pca_harmony_leiden_0.8', 'pca_harmony_leiden_1.0', 'pca_harmony_leiden_1.5', 'pca_harmony_leiden_2.0', 'pca_harmony_leiden_3.0', 'multi_celltypes_coarse', 'fine_grain_12Jun2025', 'sliding_window_assignment', 'window_col', 'window_row', 'globalX', 'globalY', 'tt_prediction'
    var: 'gene_ids', 'feature_types', 'genome', 'n_cells_by_counts-0', 'mean_counts-0', 'log1p_mean_counts-0', 'pct_dropout_by_counts-0', 'total_counts-0', 'log1p_total_counts-0', 'n_cells_by_counts-1', 'mean_counts-1', 'log1p_mean_counts-1', 'pct_dropout_by_counts-1', 'total_counts-1', 'log1p_total_counts-1'
    uns: 'celltypist_coarse2midmod_colors', 'celltypist_coarse_colors', 'celltypist_mid_fin_colors', 'dendrogram_pca_harmony_leiden_1.0', 'fine_grain_12Jun2025_colors', 'multi_celltypes_coarse_colors', 'pca', 'pca_harmony', 'pca_harmony_leiden_0.2', 'pca_harmony_leiden_0.2_colors', 'pca_harmony_leiden_0.3', 'pca_harmony_leiden_0.3_colors', 'pca_harmony_leiden_0.4', 'pca_harmony_leiden_0.4_colors', 'pca_harmony_leiden_0.5', 'pca_harmony_leiden_0.5_colors', 'pca_harmony_leiden_0.8', 'pca_harmony_leiden_0.8_colors', 'pca_harmony_leiden_1.0', 'pca_harmony_leiden_1.0_colors', 'pca_harmony_leiden_1.5', 'pca_harmony_leiden_1.5_colors', 'pca_harmony_leiden_2.0', 'pca_harmony_leiden_2.0_colors', 'pca_harmony_leiden_3.0', 'pca_harmony_leiden_3.0_colors', 'tissue_block_id_colors', 'umap'
    obsm: 'X_pca', 'X_pca_harmony', 'X_umap_pca_harmony', 'spatial'
    varm: 'PCs'
    obsp: 'pca_harmony_connectivities', 'pca_harmony_distances'
```

Example 9 (unknown):
```unknown
os.getcwd()
```

Example 10 (unknown):
```unknown
'/rfs/project/rfs-iCNyzSAaucw/kk837/notebooks/Foetal/Xenium/5K/C194_Hst45/CamU'
```

Example 11 (python):
```python
adata.X.data[:5]
```

Example 12 (unknown):
```unknown
array([5., 1., 1., 2., 2.], dtype=float32)
```

Example 13 (python):
```python
# celltype name mapping for plotting
df = pd.read_csv('/rfs/project/rfs-iCNyzSAaucw/kk837/notebooks/Foetal/finegrain_name_mapping.csv')
celltype_mapping = df.set_index('Full_name')['Short_name_finalised'].to_dict()
adata.obs.replace({celltype_key:celltype_mapping},inplace=True)
```

Example 14 (python):
```python
/tmp/ipykernel_968450/407166641.py:4: FutureWarning: The behavior of Series.replace (and DataFrame.replace) with CategoricalDtype is deprecated. In a future version, replace will only be used for cases that preserve the categories. To change the categories, use ser.cat.rename_categories instead.
  adata.obs.replace({celltype_key:celltype_mapping},inplace=True)
```

Example 15 (python):
```python
# log-normalise the count
sc.pp.normalize_total(adata,target_sum=1e4)
sc.pp.log1p(adata)
adata.X.data[:5]
```

Example 16 (unknown):
```unknown
array([4.2093534, 2.6576407, 2.6576407, 3.3151019, 3.3151019],
      dtype=float32)
```

Example 17 (python):
```python
set(adata.obs[celltype_key])
```

Example 18 (unknown):
```unknown
{'?EpendymalCells',
 '?EpithelialCells',
 '?SkeletalMuscle',
 '?ThyroidCells',
 'AVNPC',
 'AtrialCardiomyocytes_DoubletWithEC',
 'AtrialCardiomyocytes_DoubletWithFB',
 'B',
 'ChromC',
 'CorArtEC',
 'CorCapEC',
 'CorCapECCyc',
 'CorCapECN',
 'CorPeri',
 'CorSMC',
 'CorVenEC',
 'CoronaryCapillaryEndothelialCells_DoubletsWithEryth',
 'DASMC',
 'DC',
 'ELNeuro',
 'EPDC',
 'EndoCush',
 'Endocard',
 'EndocardCyc',
 'EndocardialCells_Doublets',
 'Eryth',
 'ErythCyc',
 'FB',
 'FBCOL2A1',
 'FBCyc',
 'GVArtEC',
 'GVSMC',
 'GVSMCCyc',
 'GVVenEC',
 'ILC',
 'LymphEC',
 'MPLYVE1',
 'MacCX3',
 'MastC',
 'MegaK',
 'MesEpiC',
 'Mono',
 'MyeloidCells_Doublets',
 'NeuroPre',
 'ParaN',
 'PericCyc',
 'PericFib',
 'PericInt',
 'SANPC',
 'SOX2_LAMB3_pos',
 'SchwC',
 'SchwCyc',
 'SchwP',
 'SchwannCells_DoubletsWithNeurons',
 'SympN',
 'TCD4',
 'TCD8',
 'ThyroidEpithelialCells',
 'VCSDist',
 'ValveEC',
 'aCMCyc',
 'aCML',
 'aCMR',
 'doublets',
 'unassigned',
 'unclassified',
 'vCM',
 'vCMCyc'}
```

Example 19 (python):
```python
tissue_id = 'C194-HEA-0-FFPE-1'
slide = adata[adata.obs['tissue_block_id']==tissue_id]

sc.pl.spatial(slide,color=[celltype_key],
              spot_size=15,vmax='p100',
              crop_coord=(4600,5600,4250,5250)
             )
```

Example 20 (python):
```python
/tmp/ipykernel_3227243/3010556783.py:4: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=[celltype_col],
```

Example 21 (python):
```python
tissue_id = 'C194-HEA-0-FFPE-1'
slide = adata[adata.obs['tissue_block_id']==tissue_id]

celltypes_list = ['AVNPC', 'CorCapEC', 'CorPeri', 'DASMC', 'EPDC', 'EndoCush', 'Endocard',
       'Eryth', 'FB', 'GVSMC', 'GVSMCT', 'GVVenEC', 'LymphEC', 'MPLYVE1',
       'MacCX3', 'MesEpiC', 'MoDC', 'ParaN', 'PericFib', 'SANPC', 'SchwC',
       'SchwNeuro', 'ValveEC', 'ValveIC', 'aCML', 'aCMR']
color_list = ['#ffff00',
 '#1ce6ff',
 '#ff34ff',
 '#a30059',
 '#ffdbe5',
 '#63ffac',
 '#b79762',
 '#004d43',
 '#8fb0ff',
 '#997d87',
 '#5a0007',
 'red',
 '#4a3b53',
 '#ff2f80',
 '#ba0900',
 '#6b7900',
 '#00c2a0',
 'blue',
 '#b903aa',
 (0.5, 0.0, 0.5, 0.7),
 '#7b4f4b',
 '#013349',
 '#00846f',
 '#372101',
 '#ffb500',
 '#c2ffed',
 '#cc0744',
 '#c0b9b2']

for celltype,color in zip(celltypes_list,color_list):
    # update colors
    if celltype in set(slide.obs[celltype_key]):
        slide.uns[f"{celltype_key}_colors"][list(slide.obs[celltype_key].cat.categories).index(celltype)]=color

celltypes_to_plot = ['SANPC',
                     'CorCapEC',
                     'CorPeri',
                     'GVVenEC',
                     'MesEpiC',
                     'FB',
                     'aCMR',
                     'AVNPC',
                     'ParaN',
                     'SchwP',
                    ]

sc.pl.spatial(slide,color=[celltype_key],groups=celltypes_to_plot,
              spot_size=15,vmax='p100',
              crop_coord=(4600,5600,4250,5250),
              show=False
             )
plt.savefig(f'{figdir}/Xenium5K_euploid_SAN_for-Fig1.pdf',bbox_inches="tight",dpi=300)
```

Example 22 (python):
```python
/tmp/ipykernel_3227243/2717981830.py:54: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=[celltype_key],groups=celltypes_to_plot,
/home/kk837/.conda/envs/generic_env/lib/python3.10/site-packages/scanpy/plotting/_utils.py:406: ImplicitModificationWarning: Trying to modify attribute `._uns` of view, initializing view as actual.
  adata.uns[color_key] = _palette
/home/kk837/.conda/envs/generic_env/lib/python3.10/site-packages/scanpy/plotting/_tools/scatterplots.py:1148: UserWarning: *c* argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with *x* & *y*.  Please use the *color* keyword-argument or provide a 2D array with a single row if you intend to specify the same RGB or RGBA value for all points.
  ax.scatter([], [], c=palette[label], label=label)
```

Example 23 (python):
```python
ADATA_PATH = "/rfs/project/rfs-iCNyzSAaucw/kk837/data_objects/Foetal/RNA/Feb28ObjectRaw_finegrain_updated.h5ad"
ad = sc.read_h5ad(ADATA_PATH, backed='r')

# Step 1: Create mapping (already done)
cat = "mid_grain"
mid2colours = dict(zip(ad.obs[cat].cat.categories, ad.uns[f"{cat}_colors"]))

# Step 2: Extract the labels and colors in the correct order
mid_grains = list(mid2colours.keys())
palette = list(mid2colours.values())
num_mid_grains = len(mid_grains)

# Step 3: Plot
plt.figure(figsize=(num_mid_grains * 0.4, 2))  # wide figure
sns.palplot(palette)
plt.xticks(np.arange(num_mid_grains), mid_grains, rotation=90)
plt.title("Mid Grain to Color Mapping")
plt.tight_layout()
plt.show()
```

Example 24 (python):
```python
/tmp/ipykernel_794362/455462603.py:18: UserWarning: Tight layout not applied. The bottom and top margins cannot be made large enough to accommodate all Axes decorations.
  plt.tight_layout()
```

Example 25 (unknown):
```unknown
<Figure size 448x160 with 0 Axes>
```

Example 26 (python):
```python
adata.obs['celltypist_mid_fin'] = pd.Categorical(
    adata.obs['celltypist_mid_fin'],
    categories=ad.obs[cat].cat.categories,
    ordered=True
)
```

Example 27 (python):
```python
latent_space = 'pca_harmony'
sc.pl.embedding(adata,
                    basis=f"X_umap_{latent_space}",
                    color='celltypist_mid_fin',palette=palette,
                show=False
                   )
plt.savefig(f'{figdir}/Xenium5K_UMAP-midgrain_for-Fig1.pdf',bbox_inches="tight",dpi=300)
```

Example 28 (python):
```python
tissue_id = 'C194-HEA-0-FFPE-1'
slide = adata[adata.obs['tissue_block_id']==tissue_id]

sc.pl.spatial(slide,color=['celltypist_mid_fin'],
              spot_size=15,vmax='p100',
              # crop_coord=(4600,5600,4250,5250),
              show=False
             )
# plt.savefig(f'{figdir}/Xenium5K_euploid_SAN_for-Fig1.pdf',bbox_inches="tight",dpi=300)
```

Example 29 (python):
```python
/tmp/ipykernel_794362/1888614849.py:4: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['celltypist_mid_fin'],
```

Example 30 (unknown):
```unknown
[<Axes: title={'center': 'celltypist_mid_fin'}, xlabel='spatial1', ylabel='spatial2'>]
```

Example 31 (unknown):
```unknown
AnnotationPalette={ 
    'Atrium':'#eac075',
        'Ventricle - Compact':'#f1acfa',
     'Ventricle - Trabeculated':'#f09951',
        'SAnode':'#8A2BE2',
        'AVnode':'#062b4a',
    'VCS - Proximal':'#FFFF00',
        'VCS - Distal':'#7FFFD4',
        'Epicardium':'#01ccc8',
        'Endocardium - Atrial':'#DC143C',
        'Endocardium - Ventricular':'#f53527',
        'Endocardial cusion':'#ff7e97',
        'Great vessel':'#ff9b6e',
    'Ductus arteriosus':'#8a6800',
        'Coronary vessel':'#206601',
        'Adventitia - Coronary':'#CAFF70',
     'Adventitia - GV':'#005aa0',
        'AV ring':'#e478ff',
    'Valves':'#3300FF',
    'LN':'#9088ff',
}
```

Example 32 (python):
```python
tissue_id = 'C194-HEA-0-FFPE-1'
slide = adata[adata.obs['tissue_block_id']==tissue_id]

sc.pl.spatial(slide,color=['tt_prediction'],
              spot_size=15,vmax='p100',
              # crop_coord=(4600,5600,4250,5250),
              show=False,
              palette=AnnotationPalette
             )
plt.savefig(f'{figdir}/TissueTypist_Xenium5K_whole-heart.pdf',bbox_inches="tight",dpi=300)
```

Example 33 (python):
```python
/tmp/ipykernel_968450/2063101229.py:4: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['tt_prediction'],
/home/kk837/.conda/envs/generic_env/lib/python3.10/site-packages/scanpy/plotting/_utils.py:487: ImplicitModificationWarning: Trying to modify attribute `._uns` of view, initializing view as actual.
  adata.uns[value_to_plot + "_colors"] = colors_list
```

Example 34 (python):
```python
sc.pl.spatial(slide,color=['tt_prediction'],
              spot_size=15,vmax='p100',
              crop_coord=(5500,6800,4250,5500),
              show=False,
              palette=AnnotationPalette
             )
plt.savefig(f'{figdir}/TissueTypist_Xenium5K_Atrium-AVN.pdf',bbox_inches="tight",dpi=300)
```

Example 35 (python):
```python
/tmp/ipykernel_968450/2129560865.py:1: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['tt_prediction'],
```

Example 36 (python):
```python
sc.pl.spatial(slide,color=['tt_prediction'],
              spot_size=15,vmax='p100',
              crop_coord=(8000,9500,2500,4000),
              show=False,
              palette=AnnotationPalette
             )
plt.savefig(f'{figdir}/TissueTypist_Xenium5K_Ventricle.pdf',bbox_inches="tight",dpi=300)
```

Example 37 (python):
```python
/tmp/ipykernel_968450/2311424067.py:1: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['tt_prediction'],
```

Example 38 (python):
```python
sc.pl.spatial(slide,color=['tt_prediction'],
              spot_size=15,vmax='p100',
              crop_coord=(3500,5000,1800,3300),
              show=False,
              palette=AnnotationPalette
             )
plt.savefig(f'{figdir}/TissueTypist_Xenium5K_GV.pdf',bbox_inches="tight",dpi=300)
```

Example 39 (python):
```python
/tmp/ipykernel_968450/3875201264.py:1: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['tt_prediction'],
```

---

## Notebook

**URL:** http://127.0.0.1:9020/notebooks_html/Fig2_Overview_of_cellular_niches_and_TissueTypist/tissuetypist_Xenium-5K_TissueTypist-prediction_plotting.html

**Contents:**
- Read in adata¶
- Log-normalisation¶
- Plot cell types¶
- UMAP¶
- TissueTypist niches¶

**Examples:**

Example 1 (python):
```python
import matplotlib.pyplot as plt
import scanpy as sc
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os

import matplotlib as mpl
# enables correct plotting of text
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['ps.fonttype'] = 42
```

Example 2 (python):
```python
sc.settings.set_figure_params(dpi=80)
```

Example 3 (unknown):
```unknown
os.getcwd()
```

Example 4 (unknown):
```unknown
'/rfs/project/rfs-iCNyzSAaucw/kk837/notebooks/Foetal/Xenium/5K/C194_Hst45/CamU'
```

Example 5 (unknown):
```unknown
figdir = '/rfs/project/rfs-iCNyzSAaucw/kk837/notebooks/Foetal/fetal_ms_figures'
# table_dir = '/nfs/team205/heart/fetal_ms_figures/tables/Aug2024'
```

Example 6 (unknown):
```unknown
celltype_key = 'fine_grain_12Jun2025'
```

Example 7 (python):
```python
objects_dir = '/home/kk837/rds/rds-teichlab-C9woKbOCf2Y/kk837/Foetal/anndata_objects/Xenium'
path_adata = f'{objects_dir}/C194-HEA-0-FFPE-1_Hst45-HEA-0-FFPE-1_concat_5K_filtered_raw.h5ad'
adata = sc.read_h5ad(path_adata)
adata
```

Example 8 (unknown):
```unknown
AnnData object with n_obs × n_vars = 362277 × 5001
    obs: 'cell_id', 'x_centroid', 'y_centroid', 'transcript_counts', 'control_probe_counts', 'genomic_control_counts', 'control_codeword_counts', 'unassigned_codeword_counts', 'deprecated_codeword_counts', 'total_counts', 'cell_area', 'nucleus_area', 'nucleus_count', 'segmentation_method', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'log1p_total_counts', 'pct_counts_in_top_10_genes', 'pct_counts_in_top_20_genes', 'pct_counts_in_top_50_genes', 'pct_counts_in_top_150_genes', 'n_counts', 'n_genes', 'tissue_block_id', 'celltypist_coarse', 'conf_score_coarse', 'celltypist_coarse_fin', 'celltypist_coarse2midmod', 'conf_score_coarse2midmod', 'celltypist_mid_fin', 'celltypist_midmod2fine', 'conf_score_midmod2fine', 'pca_harmony_leiden_0.2', 'pca_harmony_leiden_0.3', 'pca_harmony_leiden_0.4', 'pca_harmony_leiden_0.5', 'pca_harmony_leiden_0.8', 'pca_harmony_leiden_1.0', 'pca_harmony_leiden_1.5', 'pca_harmony_leiden_2.0', 'pca_harmony_leiden_3.0', 'multi_celltypes_coarse', 'fine_grain_12Jun2025', 'sliding_window_assignment', 'window_col', 'window_row', 'globalX', 'globalY', 'tt_prediction'
    var: 'gene_ids', 'feature_types', 'genome', 'n_cells_by_counts-0', 'mean_counts-0', 'log1p_mean_counts-0', 'pct_dropout_by_counts-0', 'total_counts-0', 'log1p_total_counts-0', 'n_cells_by_counts-1', 'mean_counts-1', 'log1p_mean_counts-1', 'pct_dropout_by_counts-1', 'total_counts-1', 'log1p_total_counts-1'
    uns: 'celltypist_coarse2midmod_colors', 'celltypist_coarse_colors', 'celltypist_mid_fin_colors', 'dendrogram_pca_harmony_leiden_1.0', 'fine_grain_12Jun2025_colors', 'multi_celltypes_coarse_colors', 'pca', 'pca_harmony', 'pca_harmony_leiden_0.2', 'pca_harmony_leiden_0.2_colors', 'pca_harmony_leiden_0.3', 'pca_harmony_leiden_0.3_colors', 'pca_harmony_leiden_0.4', 'pca_harmony_leiden_0.4_colors', 'pca_harmony_leiden_0.5', 'pca_harmony_leiden_0.5_colors', 'pca_harmony_leiden_0.8', 'pca_harmony_leiden_0.8_colors', 'pca_harmony_leiden_1.0', 'pca_harmony_leiden_1.0_colors', 'pca_harmony_leiden_1.5', 'pca_harmony_leiden_1.5_colors', 'pca_harmony_leiden_2.0', 'pca_harmony_leiden_2.0_colors', 'pca_harmony_leiden_3.0', 'pca_harmony_leiden_3.0_colors', 'tissue_block_id_colors', 'umap'
    obsm: 'X_pca', 'X_pca_harmony', 'X_umap_pca_harmony', 'spatial'
    varm: 'PCs'
    obsp: 'pca_harmony_connectivities', 'pca_harmony_distances'
```

Example 9 (unknown):
```unknown
os.getcwd()
```

Example 10 (unknown):
```unknown
'/rfs/project/rfs-iCNyzSAaucw/kk837/notebooks/Foetal/Xenium/5K/C194_Hst45/CamU'
```

Example 11 (python):
```python
adata.X.data[:5]
```

Example 12 (unknown):
```unknown
array([5., 1., 1., 2., 2.], dtype=float32)
```

Example 13 (python):
```python
# celltype name mapping for plotting
df = pd.read_csv('/rfs/project/rfs-iCNyzSAaucw/kk837/notebooks/Foetal/finegrain_name_mapping.csv')
celltype_mapping = df.set_index('Full_name')['Short_name_finalised'].to_dict()
adata.obs.replace({celltype_key:celltype_mapping},inplace=True)
```

Example 14 (python):
```python
/tmp/ipykernel_968450/407166641.py:4: FutureWarning: The behavior of Series.replace (and DataFrame.replace) with CategoricalDtype is deprecated. In a future version, replace will only be used for cases that preserve the categories. To change the categories, use ser.cat.rename_categories instead.
  adata.obs.replace({celltype_key:celltype_mapping},inplace=True)
```

Example 15 (python):
```python
# log-normalise the count
sc.pp.normalize_total(adata,target_sum=1e4)
sc.pp.log1p(adata)
adata.X.data[:5]
```

Example 16 (unknown):
```unknown
array([4.2093534, 2.6576407, 2.6576407, 3.3151019, 3.3151019],
      dtype=float32)
```

Example 17 (python):
```python
set(adata.obs[celltype_key])
```

Example 18 (unknown):
```unknown
{'?EpendymalCells',
 '?EpithelialCells',
 '?SkeletalMuscle',
 '?ThyroidCells',
 'AVNPC',
 'AtrialCardiomyocytes_DoubletWithEC',
 'AtrialCardiomyocytes_DoubletWithFB',
 'B',
 'ChromC',
 'CorArtEC',
 'CorCapEC',
 'CorCapECCyc',
 'CorCapECN',
 'CorPeri',
 'CorSMC',
 'CorVenEC',
 'CoronaryCapillaryEndothelialCells_DoubletsWithEryth',
 'DASMC',
 'DC',
 'ELNeuro',
 'EPDC',
 'EndoCush',
 'Endocard',
 'EndocardCyc',
 'EndocardialCells_Doublets',
 'Eryth',
 'ErythCyc',
 'FB',
 'FBCOL2A1',
 'FBCyc',
 'GVArtEC',
 'GVSMC',
 'GVSMCCyc',
 'GVVenEC',
 'ILC',
 'LymphEC',
 'MPLYVE1',
 'MacCX3',
 'MastC',
 'MegaK',
 'MesEpiC',
 'Mono',
 'MyeloidCells_Doublets',
 'NeuroPre',
 'ParaN',
 'PericCyc',
 'PericFib',
 'PericInt',
 'SANPC',
 'SOX2_LAMB3_pos',
 'SchwC',
 'SchwCyc',
 'SchwP',
 'SchwannCells_DoubletsWithNeurons',
 'SympN',
 'TCD4',
 'TCD8',
 'ThyroidEpithelialCells',
 'VCSDist',
 'ValveEC',
 'aCMCyc',
 'aCML',
 'aCMR',
 'doublets',
 'unassigned',
 'unclassified',
 'vCM',
 'vCMCyc'}
```

Example 19 (python):
```python
tissue_id = 'C194-HEA-0-FFPE-1'
slide = adata[adata.obs['tissue_block_id']==tissue_id]

sc.pl.spatial(slide,color=[celltype_key],
              spot_size=15,vmax='p100',
              crop_coord=(4600,5600,4250,5250)
             )
```

Example 20 (python):
```python
/tmp/ipykernel_3227243/3010556783.py:4: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=[celltype_col],
```

Example 21 (python):
```python
tissue_id = 'C194-HEA-0-FFPE-1'
slide = adata[adata.obs['tissue_block_id']==tissue_id]

celltypes_list = ['AVNPC', 'CorCapEC', 'CorPeri', 'DASMC', 'EPDC', 'EndoCush', 'Endocard',
       'Eryth', 'FB', 'GVSMC', 'GVSMCT', 'GVVenEC', 'LymphEC', 'MPLYVE1',
       'MacCX3', 'MesEpiC', 'MoDC', 'ParaN', 'PericFib', 'SANPC', 'SchwC',
       'SchwNeuro', 'ValveEC', 'ValveIC', 'aCML', 'aCMR']
color_list = ['#ffff00',
 '#1ce6ff',
 '#ff34ff',
 '#a30059',
 '#ffdbe5',
 '#63ffac',
 '#b79762',
 '#004d43',
 '#8fb0ff',
 '#997d87',
 '#5a0007',
 'red',
 '#4a3b53',
 '#ff2f80',
 '#ba0900',
 '#6b7900',
 '#00c2a0',
 'blue',
 '#b903aa',
 (0.5, 0.0, 0.5, 0.7),
 '#7b4f4b',
 '#013349',
 '#00846f',
 '#372101',
 '#ffb500',
 '#c2ffed',
 '#cc0744',
 '#c0b9b2']

for celltype,color in zip(celltypes_list,color_list):
    # update colors
    if celltype in set(slide.obs[celltype_key]):
        slide.uns[f"{celltype_key}_colors"][list(slide.obs[celltype_key].cat.categories).index(celltype)]=color

celltypes_to_plot = ['SANPC',
                     'CorCapEC',
                     'CorPeri',
                     'GVVenEC',
                     'MesEpiC',
                     'FB',
                     'aCMR',
                     'AVNPC',
                     'ParaN',
                     'SchwP',
                    ]

sc.pl.spatial(slide,color=[celltype_key],groups=celltypes_to_plot,
              spot_size=15,vmax='p100',
              crop_coord=(4600,5600,4250,5250),
              show=False
             )
plt.savefig(f'{figdir}/Xenium5K_euploid_SAN_for-Fig1.pdf',bbox_inches="tight",dpi=300)
```

Example 22 (python):
```python
/tmp/ipykernel_3227243/2717981830.py:54: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=[celltype_key],groups=celltypes_to_plot,
/home/kk837/.conda/envs/generic_env/lib/python3.10/site-packages/scanpy/plotting/_utils.py:406: ImplicitModificationWarning: Trying to modify attribute `._uns` of view, initializing view as actual.
  adata.uns[color_key] = _palette
/home/kk837/.conda/envs/generic_env/lib/python3.10/site-packages/scanpy/plotting/_tools/scatterplots.py:1148: UserWarning: *c* argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with *x* & *y*.  Please use the *color* keyword-argument or provide a 2D array with a single row if you intend to specify the same RGB or RGBA value for all points.
  ax.scatter([], [], c=palette[label], label=label)
```

Example 23 (python):
```python
ADATA_PATH = "/rfs/project/rfs-iCNyzSAaucw/kk837/data_objects/Foetal/RNA/Feb28ObjectRaw_finegrain_updated.h5ad"
ad = sc.read_h5ad(ADATA_PATH, backed='r')

# Step 1: Create mapping (already done)
cat = "mid_grain"
mid2colours = dict(zip(ad.obs[cat].cat.categories, ad.uns[f"{cat}_colors"]))

# Step 2: Extract the labels and colors in the correct order
mid_grains = list(mid2colours.keys())
palette = list(mid2colours.values())
num_mid_grains = len(mid_grains)

# Step 3: Plot
plt.figure(figsize=(num_mid_grains * 0.4, 2))  # wide figure
sns.palplot(palette)
plt.xticks(np.arange(num_mid_grains), mid_grains, rotation=90)
plt.title("Mid Grain to Color Mapping")
plt.tight_layout()
plt.show()
```

Example 24 (python):
```python
/tmp/ipykernel_794362/455462603.py:18: UserWarning: Tight layout not applied. The bottom and top margins cannot be made large enough to accommodate all Axes decorations.
  plt.tight_layout()
```

Example 25 (unknown):
```unknown
<Figure size 448x160 with 0 Axes>
```

Example 26 (python):
```python
adata.obs['celltypist_mid_fin'] = pd.Categorical(
    adata.obs['celltypist_mid_fin'],
    categories=ad.obs[cat].cat.categories,
    ordered=True
)
```

Example 27 (python):
```python
latent_space = 'pca_harmony'
sc.pl.embedding(adata,
                    basis=f"X_umap_{latent_space}",
                    color='celltypist_mid_fin',palette=palette,
                show=False
                   )
plt.savefig(f'{figdir}/Xenium5K_UMAP-midgrain_for-Fig1.pdf',bbox_inches="tight",dpi=300)
```

Example 28 (python):
```python
tissue_id = 'C194-HEA-0-FFPE-1'
slide = adata[adata.obs['tissue_block_id']==tissue_id]

sc.pl.spatial(slide,color=['celltypist_mid_fin'],
              spot_size=15,vmax='p100',
              # crop_coord=(4600,5600,4250,5250),
              show=False
             )
# plt.savefig(f'{figdir}/Xenium5K_euploid_SAN_for-Fig1.pdf',bbox_inches="tight",dpi=300)
```

Example 29 (python):
```python
/tmp/ipykernel_794362/1888614849.py:4: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['celltypist_mid_fin'],
```

Example 30 (unknown):
```unknown
[<Axes: title={'center': 'celltypist_mid_fin'}, xlabel='spatial1', ylabel='spatial2'>]
```

Example 31 (unknown):
```unknown
AnnotationPalette={ 
    'Atrium':'#eac075',
        'Ventricle - Compact':'#f1acfa',
     'Ventricle - Trabeculated':'#f09951',
        'SAnode':'#8A2BE2',
        'AVnode':'#062b4a',
    'VCS - Proximal':'#FFFF00',
        'VCS - Distal':'#7FFFD4',
        'Epicardium':'#01ccc8',
        'Endocardium - Atrial':'#DC143C',
        'Endocardium - Ventricular':'#f53527',
        'Endocardial cusion':'#ff7e97',
        'Great vessel':'#ff9b6e',
    'Ductus arteriosus':'#8a6800',
        'Coronary vessel':'#206601',
        'Adventitia - Coronary':'#CAFF70',
     'Adventitia - GV':'#005aa0',
        'AV ring':'#e478ff',
    'Valves':'#3300FF',
    'LN':'#9088ff',
}
```

Example 32 (python):
```python
tissue_id = 'C194-HEA-0-FFPE-1'
slide = adata[adata.obs['tissue_block_id']==tissue_id]

sc.pl.spatial(slide,color=['tt_prediction'],
              spot_size=15,vmax='p100',
              # crop_coord=(4600,5600,4250,5250),
              show=False,
              palette=AnnotationPalette
             )
plt.savefig(f'{figdir}/TissueTypist_Xenium5K_whole-heart.pdf',bbox_inches="tight",dpi=300)
```

Example 33 (python):
```python
/tmp/ipykernel_968450/2063101229.py:4: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['tt_prediction'],
/home/kk837/.conda/envs/generic_env/lib/python3.10/site-packages/scanpy/plotting/_utils.py:487: ImplicitModificationWarning: Trying to modify attribute `._uns` of view, initializing view as actual.
  adata.uns[value_to_plot + "_colors"] = colors_list
```

Example 34 (python):
```python
sc.pl.spatial(slide,color=['tt_prediction'],
              spot_size=15,vmax='p100',
              crop_coord=(5500,6800,4250,5500),
              show=False,
              palette=AnnotationPalette
             )
plt.savefig(f'{figdir}/TissueTypist_Xenium5K_Atrium-AVN.pdf',bbox_inches="tight",dpi=300)
```

Example 35 (python):
```python
/tmp/ipykernel_968450/2129560865.py:1: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['tt_prediction'],
```

Example 36 (python):
```python
sc.pl.spatial(slide,color=['tt_prediction'],
              spot_size=15,vmax='p100',
              crop_coord=(8000,9500,2500,4000),
              show=False,
              palette=AnnotationPalette
             )
plt.savefig(f'{figdir}/TissueTypist_Xenium5K_Ventricle.pdf',bbox_inches="tight",dpi=300)
```

Example 37 (python):
```python
/tmp/ipykernel_968450/2311424067.py:1: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['tt_prediction'],
```

Example 38 (python):
```python
sc.pl.spatial(slide,color=['tt_prediction'],
              spot_size=15,vmax='p100',
              crop_coord=(3500,5000,1800,3300),
              show=False,
              palette=AnnotationPalette
             )
plt.savefig(f'{figdir}/TissueTypist_Xenium5K_GV.pdf',bbox_inches="tight",dpi=300)
```

Example 39 (python):
```python
/tmp/ipykernel_968450/3875201264.py:1: FutureWarning: Use `squidpy.pl.spatial_scatter` instead.
  sc.pl.spatial(slide,color=['tt_prediction'],
```

---
