Skip to contents

Packages: RGraphSpace 1.5.8.1; RGraphSpaceExperiment 0.1.2

Overview

This vignette continues from Spatial-segmented data with SpatialExperiment and RGraphSpace, which ends by saving a region of interest (ROI) of a Visium HD spatial gene expression dataset from formalin-fixed paraffin-embedded (FFPE) human colorectal cancer (CRC) tissue (Oliveira et al. 2025). Here, we start with a pre-extracted ROI enriched in tumor cells, provided as a ready-to-use GraphSpaceExperiment, and infer cell-cell communication within the region with COMMOT and the CellChatDB ligand-receptor database. The inferred signals are stored back in the object as directed edges between cells, which can be drawn over the tissue, counted and filtered like any graph. Because the object is both a SingleCellExperiment and a GraphSpaceInterface (the class behind the RGraphSpace methods), the same data feed Bioconductor tools and ggplot2 plots, with no conversion between them.

Before you start

This vignette assumes familiarity with the previous vignette, where the dataset was prepared: the tissue image, scale factor, physical unit and cell outlines were set, and the region was selected by cropping. Familiarity with SpatialExperiment (Righelli et al. 2022) is also assumed.

Computational requirements:

  • Hardware: Desktop or laptop with RAM ≥ 16 GB

  • Software:

    • R (≥4.5); RStudio recommended
    • Python 3.10, for the cell-cell communication analysis (installed from R, see below)

Required packages

Before proceeding, ensure that all packages described in the Installation Instructions are installed.

# Check versions
if (packageVersion("RGraphSpace") < "1.5.8.1"){
  message("Need to update 'RGraphSpace' for this vignette")
  remotes::install_github("sysbiolab/RGraphSpace")
}
if (!requireNamespace("RGraphSpaceExperiment", quietly = TRUE)){
  remotes::install_github("sysbiolab/RGraphSpaceExperiment")
}
if (packageVersion("RGraphSpaceExperiment") < "0.1.1"){
  message("Need to update 'RGraphSpaceExperiment' for this vignette")
  remotes::install_github("sysbiolab/RGraphSpaceExperiment")
}

Setting input data

Loading the data

The ROI is available from the RGraphSpace-data repository. The file holds gse_roi2, a GraphSpaceExperiment with its assays, cell data, outlines, tissue image and coordinates, all aligned.

# Download the demonstration data
url <- paste0("https://github.com/sysbiolab/RGraphSpace-data/releases/download/",
  "v1/gs_spatial_roi2.RData")
f <- tempfile(fileext = ".RData")
download.file(url, f, mode = "wb")

# Load 'gse_roi2'
load(f)
gse_roi2
#> class: GraphSpaceExperiment 
#> dim: 18132 8771 
#> metadata(6): resouces spatialList ... scalefactors PCA
#> assays(2): counts logcounts
#> rownames(18132): SAMD11 NOC2L ... MT-ND6 MT-CYB
#> rowData names(3): ID Symbol Type
#> colnames(8771): cellid_000004100-1 cellid_000004316-1 ... cellid_000106479-1
#> colData names(5): map sample_id celltype celltype_detailed clusters
#> reducedDimNames(2): PCA UMAP
#> mainExpName: NULL
#> altExpNames(0):
#> + graph: 8771 nodes, 0 edges
#> + node attributes(4): x y nodeLabel nodeSize
#> + geometries(1): cellseg
#> + feature source: counts
#> + node spatial boundaries: normalized to image space
#> | x: [4511, 4807] -> [0, 1] (cols)
#> | y: [315, 611] -> [0, 1] (rows)
#> + image spatial boundaries: cropped to graph space
#> | x: [1, 6000] -> [1, 297] (cols)
#> | y: [1, 3886] -> [1, 297] (rows)
#> + scale factor: 0.07973
#> + coordinate unit: 0.2737 um

Overview of cell types

The ROI covers about 1 × 1 mm of the tissue section described in the previous vignette, in an area enriched in tumor cells.

# Size of the ROI (width and height), in millimeters
gs_coords_extent(gse_roi2, unit = "mm")
#>    width   height
#> 1.019503 1.019503

We first plot the cells, each outline filled by its annotated cell type.

# Set a reusable theme
my_theme <- theme_gspace_coords(theme = "th3", is_norm = TRUE, 
  xlab = "Tissue coordinates 1", ylab = "Tissue coordinates 2")

# Set cell type colors
types <- c("Tumor", "Endothelial", "Fibroblast", "Myeloid", 
  "B cells", "T cells", "Intestinal Epithelial", "Smooth Muscle",
  "Neuronal", "Unassigned")
ct_pal <- c(palette.colors(9, "Paired"), "grey")
ct_pal <- setNames(ct_pal, types)
# Fill each segmented shape by cell type
p <- ggplot(gse_roi2) +
  geom_sf(aes(geometry = cellseg, fill = celltype), colour = "white") +
  geom_nodespace(colour = "grey50", size = 0.1, pch = 19) +
  scale_fill_manual(values = ct_pal, name = "Cell type") +
  annotation_gspace_scalebar(box = TRUE) +
  my_theme

p

Cell-cell communication

Next, we infer cell-cell communication with COMMOT (Cang et al. 2023), using ligand-receptor (LR) pairs from the CellChatDB database (Jin et al. 2021). COMMOT uses collective optimal transport: each cell’s ligand signal is distributed to nearby cells expressing the receptor, within a set distance; within this range, the signal decreases with distance. COMMOT runs in Python, which we call from R with reticulate; the GraphSpaceExperiment provides the log-expression values and the cell coordinates in micrometers.

We will first set up Python and load the LR database, then select a pathway and check that its genes are expressed in the ROI. After running COMMOT, we will add its output to the object, then explore the communication results.

# Load reticulate, the R <-> Python bridge
library("reticulate")
library("anndataR")

# Stop early if Python was already started in this session with another environment
if (py_available(initialize = FALSE)) {
  stop("Python is already running in this session. Restart R and run this chunk first.")
}

Set up the Python environment

Choose one of the two options below.

Option 1: Automatically managed environment

  • Requires reticulate ≥ 1.41;
  • Restart R before running, so Python isn’t already loaded;
  • Uses its own environment, even if the working directory has another one (e.g. a .venv folder).
Show the code
# Use reticulate's managed environment
Sys.setenv(RETICULATE_PYTHON = "managed")

# Declare Python and packages: COMMOT and NumPy 1.x (COMMOT breaks on NumPy 2)
py_require(c("commot", "numpy<2"), python_version = "3.10")

Option 2: A named virtual environment

  • This should work with any reticulate version;
  • Restart R before running, so Python isn’t already loaded.
Show the code
# Install Python 3.10 (skipped if already installed)
py_path <- install_python(version = "3.10:latest")

# Environment name
env <- "commot_env"

# Start clean: remove any previous environment with this name
if (virtualenv_exists(env)) virtualenv_remove(env, confirm = FALSE)

# Create the environment with NumPy 1.x (COMMOT breaks on NumPy 2)
virtualenv_create(envname = env, python = py_path, packages = "numpy<2")

# Install COMMOT, keeping NumPy 1.x and using a prebuilt POT
virtualenv_install(env, packages = c("numpy<2", "pot", "commot"),
  pip_options = "--only-binary=pot")

# Use the environment in this session
use_virtualenv(env, required = TRUE)

Load the LR database

# Check Python is in use
py_config()

# Check that commot is importable (should print TRUE)
print(py_module_available("commot"))

# Import COMMOT into R (used to retrieve LR interactions from CellChatDB)
ct <- reticulate::import("commot")

# Retrieve LR interactions from CellChatDB
db <- ct$pp$ligand_receptor_database(
  species = "human", 
  database = "CellChat", 
  signaling_type = NULL)

names(db) <- c("ligand", "receptor", "pathway", "type")

nrow(db)
#> [1] 1939

head(db)
#>   ligand      receptor pathway               type
#> 0  TGFB1 TGFBR1_TGFBR2    TGFb Secreted Signaling
#> 1  TGFB2 TGFBR1_TGFBR2    TGFb Secreted Signaling
#> 2  TGFB3 TGFBR1_TGFBR2    TGFb Secreted Signaling
#> 3  TGFB1 ACVR1B_TGFBR2    TGFb Secreted Signaling
#> 4  TGFB1 ACVR1C_TGFBR2    TGFb Secreted Signaling
#> 5  TGFB2 ACVR1B_TGFBR2    TGFb Secreted Signaling

Select a pathway

CellChatDB groups its LR pairs into pathways of three types: secreted signaling, cell-cell contact and extracellular matrix (ECM)-receptor. Before choosing one, we check which pathways can signal in this ROI: a pathway needs cells that express its ligands, to send, and cells that express its receptors, to receive. The lrExpression() function counts these cells for each LR pair, over all cells and per cell type; lrExpressionPlot() summarizes the result by pathway, each shown by its best LR pair. Here we look at the secreted pathways.

# Share of cells expressing the ligand and the receptor of each LR pair,
# overall and per cell type (a cell expresses a gene with at least 1 count)
lr_stats <- lrExpression(gse_roi2, lr = db, group = "celltype", min_count = 1)

# Secreted signaling pathways only
lr_stats_secreted <- lr_stats[lr_stats$type == "Secreted Signaling", ]

# Pathways: share of all cells expressing the ligand and the receptor
p1 <- lrExpressionPlot(lr_stats_secreted, level = "pathway")

# Pathways: share of each cell type expressing the ligands and receptors
p2 <- lrExpressionPlot(lr_stats_secreted, level = "pathway", view = "group")

p1 + p2 + plot_layout(widths = c(1, 2), guides = "collect")

We focus on one pathway, TGF-β, and ask which cell types send and receive it in this ROI. Its receptors are widely expressed, while its ligands are expressed in few cells, below the 5% line: a typical pattern for secreted signals, with few sources and many possible receivers. Any other pathway can be set in pathway; the rest of the code follows it.

# Which cell types produce and receive TGFb signals in this ROI?
pathway <- "TGFb"
db_question <- db[db$pathway==pathway,]
nrow(db_question)
#> [1] 12

Before running the analysis, we look at the genes of the selected pathway. Since the GraphSpaceExperiment is a SingleCellExperiment, scater functions such as plotDots() work on it directly; besides the share of cells expressing each gene, it shows the average expression, and each subunit of a receptor complex on its own.

# Parse ligand and receptor genes
parse_genes <- function(x, genes) {
  intersect(unique(unlist(strsplit(x, "_"))), genes)
}
ligands <- parse_genes(db_question$ligand, rownames(gse_roi2))
receptors <- parse_genes(db_question$receptor, rownames(gse_roi2))

# Check ligand expression
p1 <- plotDots(gse_roi2, features = ligands, group = "celltype") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(y = "Ligands")

# Check receptor expression
p2 <- plotDots(gse_roi2, features = receptors, group = "celltype") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(y = "Receptors")

p1 + p2

Infer communication

We pass the log-expression values and the cell coordinates, in micrometers, to COMMOT. The physical unit set in the previous vignette makes the signaling range a real distance: here, 250 µm.

# Build AnnData: log-expression and coordinates
ad <- AnnData(
  X = Matrix::t(logcounts(gse_roi2)),
  obsm = list(spatial = gs_coords(gse_roi2, unit = "um"))
)
ad <- ad$as_ReticulateAnnData()

# Signaling range, in the units of the coordinates 
# (here micrometers)
dis_thr <- 250

# Run COMMOT
ct$tl$spatial_communication(ad,
  database_name = "CellChatDB",
  dis_thr = dis_thr,  
  df_ligrec = db_question,
  heteromeric = TRUE,
  pathway_sum = TRUE,
  heteromeric_rule = "min",
  heteromeric_delimiter = "_")

Add results to GraphSpaceExperiment

COMMOT stores its results in the AnnData object. We move them into gse_roi2, each to its standard place: the settings of the run, with the LR pairs used, to metadata(); the sender and receiver scores of each cell, for every LR pair and for the pathway as a whole, to colData(), where their columns can be used by name in plots; and the cell-to-cell signals to colPairs(), the slot of a SingleCellExperiment for values between pairs of cells. From here on, all results are read from gse_roi2.

# Run information recorded by COMMOT
info <- ad$uns[["commot-CellChatDB-info"]]

# COMMOT run: signaling range (µm), LR pairs, database and pathway
metadata(gse_roi2)$commot <- list(
  dis_thr = info$distance_threshold,
  lr_pairs = info$df_ligrec,
  database = "CellChatDB",
  pathway = pathway)

# Sender and receiver scores of each cell, per LR pair and for the pathway
gse_roi2$sender <- ad$obsm$`commot-CellChatDB-sum-sender`
gse_roi2$receiver <- ad$obsm$`commot-CellChatDB-sum-receiver`
head(colnames(gse_roi2$sender))
#> [1] "s-TGFB2-ACVR1B_TGFBR2"       "s-TGFB2-ACVR1_TGFBR1_TGFBR2"
#> [3] "s-TGFB2-TGFBR1_TGFBR2"       "s-TGFB2-ACVR1C_TGFBR2"      
#> [5] "s-TGFB3-ACVR1B_TGFBR2"       "s-TGFB3-ACVR1_TGFBR1_TGFBR2"

Next, we store the cell-to-cell signals, one matrix for the pathway and one for each LR pair used.

# LR pairs used by COMMOT: those with all genes in the data
lr <- metadata(gse_roi2)$commot$lr_pairs

# Cell-to-cell signals, senders (rows) to receivers (columns):
# one matrix for the pathway, and one per LR pair
for (x in c(pathway, paste(lr$ligand, lr$receptor, sep = "-"))) {
  colPair(gse_roi2, x) <- ad$obsp[[paste0("commot-CellChatDB-", x)]]
}
head(colPairNames(gse_roi2))
#> [1] "TGFb"                      "TGFB1-TGFBR1_TGFBR2"      
#> [3] "TGFB2-TGFBR1_TGFBR2"       "TGFB3-TGFBR1_TGFBR2"      
#> [5] "TGFB1-ACVR1B_TGFBR2"       "TGFB1-ACVR1C_TGFBR2"

From the pathway’s cell-to-cell signals, now in colPairs(), we take the strongest and set them as directed edges of the graph, from sender to receiver, with the cell types of both cells as edge attributes. Signals from a cell to itself (autocrine) are kept as loops, with simplify = FALSE. The graph of cells now holds the inferred communication.

# Signals sent from cell to cell for the pathway: senders (rows) to receivers (columns)
P <- colPair(gse_roi2, pathway, asSparse = TRUE)

# One row per signal: sender (i), receiver (j) and signal (x)
e <- Matrix::summary(P)

# Strongest 5% of signals, including self-signals
e <- e[e$x > quantile(e$x, 0.95), ]

# Set edges from sender to receiver
gs_set_edges(gse_roi2, directed = TRUE, 
  simplify = FALSE) <- data.frame(
  from = colnames(gse_roi2)[e$i],
  to = colnames(gse_roi2)[e$j],
  weight = e$x,
  sender_type = gse_roi2$celltype[e$i],
  receiver_type = gse_roi2$celltype[e$j])

# The graph now holds the signals as directed, weighted edges
gs_graph(gse_roi2)
#> IGRAPH 9ed5e21 DNW- 8771 2168 -- 
#> + attr: x (v/n), y (v/n), name (v/c), nodeLabel (v/c), nodeSize
#> | (v/n), arrowType (e/c), weight (e/n), sender_type (e/x),
#> | receiver_type (e/x)
#> + edges from dbc9510 (vertex names):
#>  [1] cellid_000006823-1->cellid_000007979-1
#>  [2] cellid_000006823-1->cellid_000047132-1
#>  [3] cellid_000006823-1->cellid_000048513-1
#>  [4] cellid_000006823-1->cellid_000049922-1
#>  [5] cellid_000006823-1->cellid_000049976-1
#>  [6] cellid_000006823-1->cellid_000054938-1
#> + ... omitted several edges

Exploring the communication

Signals between cells

The edges can now be drawn over the tissue: each arrow is a signal from a sending cell to a receiving one, colored by the sender’s cell type.

# Signals over the cell outlines, colored by sending cell type
p <- ggplot(gse_roi2) +
  geom_sf(aes(geometry = cellseg, fill = celltype),
    colour = "white", lwd = 0.2, alpha = 0.2) +
  geom_edgespace(aes(colour = sender_type), linewidth = 0.3,
    curve = 0.2, arrow_size = 0.5) +
  scale_fill_manual(values = ct_pal, guide = "none") +
  scale_colour_manual(values = ct_pal, name = "Sender type") +
  annotation_gspace_scalebar(box = TRUE) + 
  guides(colour = guide_legend(override.aes = list(linewidth = 2))) +
  my_theme

p

Signals between cell types

The edges are data as well as lines on the plot: each records the cell types of its sender and receiver. Counting the edges by these two attributes gives the number of connections between cell types, among the strongest signals kept as edges.

# Number of connections between cell types: senders (rows) to receivers (columns)
links <- table(gs_edges(gse_roi2)[, c("sender_type", "receiver_type")])

p <- ggplot(as.data.frame(links), 
  aes(receiver_type, sender_type, fill = Freq)) +
  geom_tile(colour = "white") +
  geom_text(aes(label = Freq), size = 3, colour = "white") +
  scale_fill_viridis_c(option = "H", end = 0.75, name = "Connections") +
  labs(title = paste(pathway, "signaling between cell types"),
    x = "Receiver cell type", y = "Sender cell type") +
  coord_fixed() + theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

p

Signaling by LR pair and cell type

We average the sender and receiver scores per cell type, for each LR pair. This shows which pairs each cell type uses to send and to receive the signal, for example which ligand dominates in each cell type, and through which receptor it is received.

# Cell type
cl <- droplevels(gse_roi2$celltype)

# Mean sender and receiver score per cell type (rows) and LR pair (columns)
s_score_mean <- rowsum(gse_roi2$sender, cl) / as.vector(table(cl))
r_score_mean <- rowsum(gse_roi2$receiver, cl) / as.vector(table(cl))

# LR pairs only: drop the total and the pathway sum
s_score_mean <- s_score_mean[, !colnames(s_score_mean) %in% 
  c("s-total-total", paste0("s-", pathway)), drop = FALSE]
r_score_mean <- r_score_mean[, !colnames(r_score_mean) %in% 
  c("r-total-total", paste0("r-", pathway)), drop = FALSE]

# Sender heatmap: LR pairs (rows) across cell types (columns)
pheatmap(t(s_score_mean), main = "Sender")

# Receiver heatmap: LR pairs (rows) across cell types (columns)
pheatmap(t(r_score_mean), main = "Receiver")

Interactions between cell types

Each LR pair links a sending cell type to a receiving one. For each LR pair, colPairs() holds a cell-by-cell signal matrix, like P for the whole pathway. We sum each matrix over the cells of each type, giving the total signal from every cell type to every other one through that pair. The result is a table with one row per sender type, receiver type and LR pair.

# LR pairs used by COMMOT
lr <- metadata(gse_roi2)$commot$lr_pairs

# Cell-type membership: one row per cell type, one column per cell,
# with 1 where the cell belongs to the type
membership <- Matrix::fac2sparse(droplevels(gse_roi2$celltype))

# Total signal from each cell type to each other, one LR pair at a time
df <- NULL
for (k in seq_len(nrow(lr))) {
  #--- Cell-to-cell signals of the LR pair
  lr_name <- paste(lr$ligand[k], lr$receptor[k], sep = "-")
  P_lr <- colPair(gse_roi2, lr_name, asSparse = TRUE)
  #--- Summed over the cells of each type: senders (rows) x receivers (columns)
  S <- as.matrix(membership %*% P_lr %*% Matrix::t(membership))
  #--- One row per pair of cell types
  df <- rbind(df, data.frame(source = rownames(S)[row(S)], 
    target = colnames(S)[col(S)], score = as.vector(S), 
    ligand = lr$ligand[k], receptor = lr$receptor[k]))
}

We show the strongest 5% of these links in a circos plot, where the width of each link is the number of LR pairs connecting the two cell types.

# Top 5% of interactions
df_top <- df[df$score > quantile(df$score, 0.95), ]

# Circos plot of cell-cell interactions
cc_circos(df_top, cell_cols = ct_pal)

Spatial maps of sending and receiving

Next, we map the pathway’s sender and receiver scores onto the cell outlines. Cells with no signal are left transparent.

# Set color palette for the scores
cpal <- hcl.colors(100, palette = "Spectral", rev = TRUE)

# Set sender/receiver names
sender <- paste("s", pathway, sep="-")
receiver <- paste("r", pathway, sep="-")

p1 <- ggplot(gse_roi2) + 
  geom_sf( aes(geometry = cellseg, fill = !!sym(sender),
    alpha = as.numeric(!!sym(sender) > 0)), 
    colour = "white", lwd = 0.5) +
  geom_nodespace(colour = "grey70", size = 0.1, pch = 19) +
  annotation_gspace_scalebar(box = TRUE) +
  scale_fill_continuous(palette = cpal, 
    limits = c(0, 2), oob = scales::squish, 
    name = paste(pathway, "sender")) +
  scale_alpha_identity() + my_theme

p2 <- ggplot(gse_roi2) + 
  geom_sf( aes(geometry = cellseg, fill = !!sym(receiver),
    alpha = as.numeric(!!sym(receiver) > 0)), 
    colour = "white", lwd = 0.5) +
  geom_nodespace(colour = "grey70", size = 0.1, pch = 19) +
  annotation_gspace_scalebar(box = TRUE) +
  scale_fill_continuous(palette = cpal, 
    limits = c(0, 2), oob = scales::squish, 
    name = paste(pathway, "receiver")) +
  scale_alpha_identity() + my_theme

p1 + p2

Direction of outgoing signals

The cell-to-cell signals also tell where each cell sends its signal. For each sending cell, we take the center of its signal: the average position of its receivers, weighted by the signal each one receives. An arrow pointing from the cell toward this center shows where its signal goes. COMMOT provides a related summary with communication_direction() (Cang et al. 2023), which by default averages the directions to each cell’s five strongest receivers, regardless of their distance, and so points toward the nearest partners; here we use all receivers. As with the sender and receiver scores, we store the results in colData().

# Signals sent from cell to cell for the pathway: senders (rows) to receivers (columns)
P <- colPair(gse_roi2, pathway, asSparse = TRUE)

# Outgoing vector of each cell (dx, dy): an offset from the cell toward its
# receivers, each weighted by the signal it gets, so that the cells
# receiving most of the signal pull the direction more
xy <- gs_coords(gse_roi2)
v <- as.matrix(P %*% xy) - rowSums(P) * xy
colnames(v) <- c("dx", "dy")

# Store the outgoing vectors as cell data
gse_roi2$outgoing_vector <- as.data.frame(v)

Each arrow points in the direction of the cell’s outgoing vector. Its length shows the coherence of the signal: how consistently the receivers lie in that direction, from balanced around the cell (short) to all on one side (long). We use the squared coherence, which stresses senders whose receivers lie mostly on one side. Cells that send nothing have no direction (NaN) and get no arrow.

# Maximum possible magnitude of each outgoing vector
# (as if all receivers were on one side)
#--- One row per signal: sender (i), receiver (j) and signal (x)
s <- Matrix::summary(P)
#--- Distance from each sender to its receiver
d <- sqrt(rowSums((xy[s$j, ] - xy[s$i, ])^2))
#--- Reach of each cell: total signal sent x distance
reach <- rowSums(sparseMatrix(s$i, s$j, x = s$x * d, dims = dim(P)))

# Actual magnitude and coherence
#--- Magnitude of each outgoing vector
mag <- sqrt(rowSums(v^2))
#--- Coherence (0 to 1): actual / maximum magnitude;
#--- NaN for cells that send nothing
coh <- mag / reach

# Arrow of each sending cell, pointing the same way as v
#--- Arrow length, from squared coherence (stresses one-sided senders)
len <- scales::rescale(coh^2, to = c(0.01, 0.04))
#--- How far the arrow tip lies from the cell, in x (ax) and in y (ay),
#--- stored with the outgoing vectors
gse_roi2$outgoing_vector$ax <- len * v[, 1] / mag
gse_roi2$outgoing_vector$ay <- len * v[, 2] / mag

We then draw the arrows over the cell outlines, each starting at its sending cell.

# Net direction of outgoing signals from each sending cell
p <- ggplot(gse_roi2) +
  geom_sf(aes(geometry = cellseg, fill = celltype), 
    colour = "white", lwd = 0.2) +
  geom_segment(aes(x, y, xend = x + ax, yend = y + ay), 
    colour = "black", arrow = arrow(length = unit(0.2, "cm")), 
    linewidth = 0.5, na.rm = TRUE) +
  scale_fill_manual(values = ct_pal, name = "Cell type") +
  labs(title = paste("Net direction of outgoing", pathway, "signals")) +
  annotation_gspace_scalebar(box = TRUE) +
  my_theme

p

Each arrow accounts for all receivers within the signaling range (here 250 µm), so together the arrows show where the signal goes across the region; long arrows mark senders whose signal goes mostly one way.

Direction of incoming signals

The same view applies to the receiving cells. With senders and receivers swapped, the incoming vector of each cell points toward the center of its senders, where its signal comes from. Arrow lengths follow the same rule as above; each arrow ends at its receiving cell, arriving from the direction of its senders.

# Incoming vector of each cell (rdx, rdy): as the outgoing vector, with
# senders and receivers swapped; it points toward the cell's senders
w <- as.matrix(Matrix::t(P) %*% xy) - colSums(P) * xy
colnames(w) <- c("rdx", "rdy")
gse_roi2$incoming_vector <- as.data.frame(w)
# Coherence and arrows, as for the outgoing vectors
#--- Reach of each cell: total signal received x distance
reach_r <- colSums(sparseMatrix(s$i, s$j, x = s$x * d, dims = dim(P)))
#--- Coherence (0 to 1); NaN for cells that receive nothing
mag_r <- sqrt(rowSums(w^2))
coh_r <- mag_r / reach_r
#--- Arrow length, from squared coherence
len_r <- scales::rescale(coh_r^2, to = c(0.01, 0.04))
#--- How far the arrow tail lies from the cell (rax, ray)
gse_roi2$incoming_vector$rax <- len_r * w[, 1] / mag_r
gse_roi2$incoming_vector$ray <- len_r * w[, 2] / mag_r

We then draw the arrows over the cell outlines, each ending at its receiving cell.

# Net direction of incoming signals at each receiving cell
p <- ggplot(gse_roi2) +
  geom_sf(aes(geometry = cellseg, fill = celltype), 
    colour = "white", lwd = 0.2) +
  geom_segment(aes(x + rax, y + ray, xend = x, yend = y), 
    colour = "black", arrow = arrow(length = unit(0.2, "cm")), 
    linewidth = 0.5, na.rm = TRUE) +
  scale_fill_manual(values = ct_pal, name = "Cell type") +
  labs(title = paste("Net direction of incoming", pathway, "signals")) +
  annotation_gspace_scalebar(box = TRUE) +
  my_theme

p

Together with the previous map, the arrows show both where the signal goes and where it comes from; long arrows mark receivers whose signal comes mostly from one side.

How far the signal reaches

Within the signaling range, COMMOT weighs each transfer by distance: the signal decays exponentially, over a length of about a tenth of the range (here, about 25 µm). We check this on the cell-to-cell signals, with distances in micrometers.

# Signals sent from cell to cell for the pathway: senders (rows) to receivers (columns)
P <- colPair(gse_roi2, pathway, asSparse = TRUE)

# One row per signal: sender (i), receiver (j) and signal (x)
sig <- Matrix::summary(P)

# Distance from each sender to its receiver, in micrometers
xy_um <- gs_coords(gse_roi2, unit = "um")
sig$distance <- sqrt(rowSums((xy_um[sig$j, ] - xy_um[sig$i, ])^2))

# Decay length: distance over which the signal falls by a factor e (~2.7)
fit <- lm(log(x) ~ distance, data = sig)
-1 / coef(fit)[["distance"]]
#> [1] 27.77096
# Signal by distance, on a log scale; dashed: the signaling range
p <- ggplot(as.data.frame(sig), aes(distance, x)) +
  geom_point(alpha = 0.05, size = 0.3) +
  geom_smooth(method = "lm", formula = y ~ x, colour = "red") +
  geom_vline(xintercept = metadata(gse_roi2)$commot$dis_thr, 
    linetype = "dashed") +
  scale_y_log10() +
  labs(x = "Distance from sender to receiver (µm)", y = "Signal",
    title = paste(pathway, "signal by distance")) +
  theme_bw() + theme(aspect.ratio = 1)

p

The signal falls about threefold every 28 µm, close to the expected 25 µm, so most of it reaches cells within about 50 µm, well inside the 250 µm range. The arrows in the previous sections therefore mostly reflect nearby receivers and senders.

Session information

#> R version 4.6.2 (2026-10-29)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.5 LTS
#> 
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so;  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> time zone: America/Sao_Paulo
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] CCPlotR_1.10.0              pheatmap_1.0.13            
#>  [3] scater_1.40.2               scuttle_1.22.0             
#>  [5] patchwork_1.3.2             Matrix_1.7-6               
#>  [7] SpatialExperiment_1.24.0    SingleCellExperiment_1.36.0
#>  [9] SummarizedExperiment_1.44.0 Biobase_2.74.0             
#> [11] GenomicRanges_1.66.0        Seqinfo_1.4.0              
#> [13] IRanges_2.48.0              S4Vectors_0.52.0           
#> [15] BiocGenerics_0.60.0         generics_0.1.4             
#> [17] MatrixGenerics_1.26.0       matrixStats_1.5.0          
#> [19] RGraphSpaceExperiment_0.1.2 RGraphSpace_1.5.8.1        
#> [21] ggplot2_4.0.4              
#> 
#> loaded via a namespace (and not attached):
#>   [1] RColorBrewer_1.1-3    rstudioapi_0.19.0     jsonlite_2.0.0       
#>   [4] shape_1.4.6.1         magrittr_2.0.5        ggbeeswarm_0.7.3     
#>   [7] magick_2.9.1          farver_2.1.2          rmarkdown_2.32       
#>  [10] GlobalOptions_0.1.4   fs_2.1.0              ragg_1.5.2           
#>  [13] vctrs_0.7.3           memoise_2.0.1         htmltools_0.5.9      
#>  [16] S4Arrays_1.14.0       forcats_1.0.1         BiocNeighbors_2.6.0  
#>  [19] SparseArray_1.13.5    sass_0.5.0            KernSmooth_2.23-27   
#>  [22] bslib_0.12.0          htmlwidgets_1.6.4     desc_1.4.3           
#>  [25] fontawesome_0.5.3     plyr_1.8.9            cachem_1.1.0         
#>  [28] igraph_2.3.4          lifecycle_1.0.5       iterators_1.0.14     
#>  [31] pkgconfig_2.0.3       rsvd_2.0.0            R6_2.6.1             
#>  [34] fastmap_1.2.0         clue_0.3-68           digest_0.6.39        
#>  [37] colorspace_2.1-4      irlba_2.4.1           textshaping_1.1.0    
#>  [40] beachmat_2.28.0       polyclip_1.10-7       abind_1.4-8          
#>  [43] compiler_4.6.2        proxy_0.4-29          withr_3.0.3          
#>  [46] doParallel_1.0.17     S7_1.0.0              BiocParallel_1.46.0  
#>  [49] viridis_0.6.5         DBI_1.3.0             ggforce_0.6.0        
#>  [52] MASS_7.3-66           DelayedArray_0.40.0   rjson_0.2.23         
#>  [55] classInt_0.4-11       tools_4.6.2           units_1.0-1          
#>  [58] vipor_0.4.7           otel_0.3.0            beeswarm_0.4.0       
#>  [61] scatterpie_0.2.6      glue_1.8.1            gridtext_0.1.6       
#>  [64] grid_4.6.2            sf_1.1-3              cluster_2.1.8.3      
#>  [67] gtable_0.3.6          class_7.3-24          tidyr_1.3.2          
#>  [70] BiocSingular_1.28.1   tidygraph_1.3.1       ScaledMatrix_1.20.0  
#>  [73] xml2_1.6.0            XVector_0.54.0        stringr_1.6.0        
#>  [76] ggrepel_0.9.8         foreach_1.5.2         pillar_1.11.1        
#>  [79] yulab.utils_0.2.7     circlize_0.4.18       dplyr_1.2.1          
#>  [82] ggtext_0.2.0          tweenr_2.0.3          lattice_0.23-1       
#>  [85] tidyselect_1.2.1      ComplexHeatmap_2.28.0 knitr_1.52           
#>  [88] gridExtra_2.3.1       xfun_0.62             graphlayouts_1.2.5   
#>  [91] stringi_1.8.9         ggfun_0.2.2           yaml_2.3.12          
#>  [94] evaluate_1.0.5        codetools_0.2-20      ggraph_2.2.2         
#>  [97] tibble_3.3.1          cli_3.6.6             systemfonts_1.3.4    
#> [100] jquerylib_0.1.4       dichromat_2.0-1       Rcpp_1.1.2           
#> [103] png_0.1-9             ggrastr_1.0.3         parallel_4.6.2       
#> [106] pkgdown_2.2.1         ggh4x_0.3.1           viridisLite_0.4.3    
#> [109] scales_1.4.0          e1071_1.7-17          purrr_1.2.2          
#> [112] crayon_1.5.3          GetoptLong_1.1.1      rlang_1.3.0

References

Cang, Zixuan, Yanxiang Zhao, Axel A. Almet, et al. 2023. “Screening Cell-Cell Communication in Spatial Transcriptomics via Collective Optimal Transport.” Nature Methods 20 (2): 218–28. https://doi.org/10.1038/s41592-022-01728-4.
Jin, Suoqin, Christian F. Guerrero-Juarez, Lihua Zhang, et al. 2021. “Inference and Analysis of Cell-Cell Communication Using CellChat.” Nature Communications 12: 1088. https://doi.org/10.1038/s41467-021-21246-9.
Oliveira, MF, JP Romero, M Chung, et al. 2025. “High-Definition Spatial Transcriptomic Profiling of Immune Cell Populations in Colorectal Cancer.” Nature Genetics 57 (6): 1512–23. https://doi.org/10.1038/s41588-025-02193-3.
Righelli, Dario, Lukas M. Weber, Helena L. Crowell, et al. 2022. “SpatialExperiment: Infrastructure for Spatially-Resolved Transcriptomics Data in r Using Bioconductor.” Bioinformatics 38 (11): –3. https://doi.org/https://doi.org/10.1093/bioinformatics/btac299.