CellDiff enhances visualization and statistical analysis of cell-cell communication differences between experimental groups.
CellDiff is an R package that extends the functionality of CellChat by providing specialized tools for differential cell-cell communication analysis between multiple conditions. While CellChat enables the inference and analysis of cell-cell communication networks from single-cell RNA sequencing data, CellDiff focuses on identifying and visualizing the differences in these communication patterns across biological conditions (e.g., normal vs. disease, treated vs. untreated, multiple genotypes).
- Multi-group comparison: Compare cell-cell communication across multiple conditions simultaneously
- Flexible comparison methods: Support for all-vs-all, all-vs-reference, and custom pairwise comparisons
- Cell type alignment: Handle missing cell types with "shared" or "union" strategies
- Differential pathway analysis: Identify signaling pathways that are significantly altered between conditions
- Advanced visualization options:
- Show all pathways with significance indicators (stars, fading)
- Comparison-specific pathway display
- Named list outputs for easier data access
- Rich visualizations: Venn diagrams, UpSet plots, heatmaps, network graphs, and timeline plots
- Ligand-receptor analysis: Compare L-R pair contributions with customizable plots and heatmaps
- Pattern discovery: Identify common and unique signaling patterns across conditions
- Sender-receiver analysis: Analyze how cells change their roles as signaling senders or receivers
- Integrated visualizations: ComplexHeatmap integration with consistent color schemes
- No external dependencies on dplyr/tidyr: Pure base R + specialized visualization packages
# Install devtools if not already installedif (!requireNamespace("devtools", quietly=TRUE))
install.packages("devtools")
# Install CellDiff from GitHubdevtools::install_github("guokai8/CellDiff")CellDiff requires the following packages:
- CellChat (>= 1.1.0)
- ggplot2
- reshape2
- circlize
- ComplexHeatmap
- cowplot
- igraph
- ggrepel
- scales
- VennDetail (optional, for Venn diagrams)
- grid
FIXED: Spatial Parameter Error in runCellChat()
- Issue: Using
interaction.rangeorcontact.dependentwith non-spatial data caused error: "unused argument" - Root cause: Spatial parameters were always passed to CellChat, but only valid for spatial transcriptomics data
- Solution: Spatial parameters now only passed when
distance.use = TRUE - Default change:
distance.usenow defaults toFALSE(most users have regular scRNA-seq data)
Usage for non-spatial data (default):
results<- runCellChat(
seurat_object,
group.by="condition",
species="mouse",
cell.type.column="cell_type"
)Usage for spatial transcriptomics data:
results<- runCellChat(
spatial_seurat_object,
group.by="condition",
species="mouse",
distance.use=TRUE, # Enable spatial modeinteraction.range=250, # Now works correctlycontact.dependent=TRUE# Now works correctly
)FIXED: Visualization Rendering Issues in rankDiff()
- Issue: Stacked bar plots showed blank spaces when pathways existed in only one experimental group
- Root cause: ggplot2's
position="fill"creates rendering artifacts with exact zeros - Solution: Added zero replacement (1e-20) after scaling to prevent rendering artifacts while keeping all significant pathways visible
- Impact: All pathways now render correctly - pathways present in only one group show as solid colored bars
- Files affected: R/rankDiff.R (line 345), R/rankDiffM.R (lines 610-615, 856)
FIXED: runCellChat Parameter Defaults
- Issue:
runCellChat()produced different results than manual CellChat pipelines - Root cause: Three parameters had incorrect defaults that didn't match CellChat's actual defaults
- Changes made (R/runCellChat.R):
population.size: Changed fromTRUE→FALSE(line 169)thresh.pc: Changed from0.1→0(line 179)thresh.fc: Changed from0.1→0(line 180)
- Impact:
runCellChat()now produces identical results to manual CellChat workflows - Breaking change: If you were using
runCellChat()before, results will change (but be more correct) - Migration: To restore old behavior, explicitly set:
population.size = TRUE, thresh.pc = 0.1, thresh.fc = 0.1
IMPROVED: rankDiff() Return Value
- NEW:
return.dataparameter to control what is returned - Default behavior: Returns plot directly (easier to display)
- With return.data = TRUE: Returns full list including plot, data, and top pathways
- Example:
plot <- rankDiff(celllist)orresults <- rankDiff(celllist, return.data = TRUE)
NEW: Comprehensive CellChat Parameter Control
runCellChatnow exposes 39 parameters for complete CellChat customization- Data Access: Choose specific assay and slot/layer (Seurat v4/v5 compatible)
- Database: Subset by interaction type or provide custom databases
- Spatial Data: Full support for spatial communication parameters
- Advanced Filtering: Control expression thresholds, cell filtering, and rare interactions
- Error Handling: Continue processing if some conditions fail (
stop.on.error = FALSE) - Flexible Returns: Get merged objects and pre-aggregation objects
- Verbosity Control: Suppress CellChat messages while keeping CellDiff progress
- See Option 3 below for full parameter details
Enhanced Cell Type Alignment
- NEW:
cell.type.strategyparameter for handling missing cell types across conditions - "shared" strategy: Uses only cell types present in all conditions (safer, more conservative)
- "union" strategy: Uses all cell types from any condition, filling missing data with zeros
- Automatically reports alignment statistics and warns about missing cell types
- Available in:
rankDiffM,heatDiffM,scatterDiff2DM, andContriDiffM
- NEW:
Advanced Comparison Visualization (rankDiffM)
- NEW:
show.allparameter for comprehensive pathway visualization - show.all = FALSE (default): Shows only pathways significant in each specific comparison
- show.all = TRUE: Shows all pathways with visual indicators:
- Faded bars (alpha=0.3) for non-significant pathway-comparison combinations
- Significance stars (*p<0.05, **p<0.01, ***p<0.001)
- Informative subtitle explaining the visualization
- FIXED: Comparison-specific pathway display - pathways now only appear in panels where they're actually significant
- FIXED: Star assignment bug - stars now only appear for pathways passing both p-value AND fold-change thresholds
- NEW:
Named List Output
- NEW: All output lists now have meaningful comparison names
- Access results by comparison name instead of numeric index
- Example:
results$all_significant_paths_full[["KO vs WT"]]instead of[[1]] - Applies to:
all_significant_paths_full,all_significant_paths,data,plots,heatmaps
Custom Pairwise Comparisons
rankDiffM,heatDiffM,scatterDiff2DM, andContriDiffMnow supportcomparison_method = "custom_pairs"- Specify exactly which condition pairs to compare:
custom_comparisons = list(c("WT", "KO"), c("KO", "DKO")) - Generates focused visualizations for your specific comparisons of interest
Enhanced findCommonUniquePatterns
- NEW: Venn diagram visualization using VennDetail (up to 7 conditions)
- NEW: UpSet plot for complex multi-way intersections
- NEW: Barplot showing total, unique, and common pattern counts
- NEW: Network visualization of top signaling interactions
- Identifies patterns that are shared or unique across conditions
Improved compareCellChatsM
- FIXED: Replaced pheatmap with ComplexHeatmap for consistency
- FIXED: Removed dplyr dependency - uses pure base R
- NEW: Enhanced timeline plots with optional labeling
- NEW: Pathway contribution timeline with labeling support
- Better color consistency across all visualizations
NEW Wrapper Functions for Streamlined Workflows
- runCellChat: One-step CellChat object creation from Seurat
- Automatically splits Seurat object by condition
- Creates and processes CellChat objects for each condition
- NEW:
run.analysisparameter for optional automatic differential analysisrun.analysis = FALSE(default): Returns CellChat objects onlyrun.analysis = TRUE: Automatically runscompareCell()and returns complete results
- Returns named list of CellChat objects OR complete analysis results
- Simplifies entire workflow from Seurat to results
- compareCell: Comprehensive differential analysis wrapper
- Automatically runs
rankDiffM,heatDiffM,scatterDiff2DM, andnetworkLRDiff - Organizes results with meaningful names and summary statistics
- Provides informative progress messages
- Returns structured CellDiffAnalysis object
- Simplifies complex differential analysis workflows
- Automatically runs
- runCellChat: One-step CellChat object creation from Seurat
Tutorial Dataset
- NEW:
pbmc_tutorial- Synthetic Seurat object for testing- 1,500 cells across 3 conditions (WT, KO, DKO)
- 5 cell types (T_cells, B_cells, Monocytes, NK_cells, Dendritic)
- Perfect for learning and testing the workflow
- Access with
data(pbmc_tutorial)
- NEW:
Bug Fixes
- Fixed RStudio display issues in
heatDiffM(changedinvisible()toreturn()) - Fixed custom_pairs index conversion in all multi-condition functions
- Fixed missing
scPalette()reference (replaced withassignColors()) - Fixed width/height swap in big_heatmap mode
- Fixed pathway display in comparison plots to be comparison-specific
- Fixed RStudio display issues in
- No breaking changes - all existing code will continue to work
pheatmapdependency removed in favor ofComplexHeatmapdplyrandtidyrare no longer required- VennDetail is optional (only needed for
findCommonUniquePatternsVenn diagrams)
CellDiff provides three flexible workflows depending on your starting point:
Perfect for beginners or quick analysis:
library(CellDiff)
# Load tutorial data
data(pbmc_tutorial)
# One-step: Create CellChat objects AND run chosen analysesresults<- runCellChat(
seurat_object=pbmc_tutorial,
group.by="condition",
species="human",
run.analysis=TRUE, # Automatic differential analysisreference="WT",
show_plots= c("barplot", "heatmap", "scatter") # Choose which analyses
)
# Access everythingresults$cellchat_objects[["WT"]] # CellChat objectsresults$pathway_analysis$comparison_barplotresults$heatmap# Only if "heatmap" in show_plotsresults$scatter# Only if "scatter" in show_plotsresults$summary# Available analyses: "barplot", "heatmap", "slope", "scatter", "network"For custom analysis workflows:
library(CellDiff)
data(pbmc_tutorial)
# Step 1: Create CellChat objects onlycellchat_list<- runCellChat(
seurat_object=pbmc_tutorial,
group.by="condition",
species="human"
)
# Step 2: Choose which analyses to run
rankDiffM(cellchat_list, reference="WT")
heatDiffM(cellchat_list, reference="WT", measure="sender")
scatterDiff2DM(cellchat_list, reference="WT")
# Or run comprehensive analysisresults<- compareCell(cellchat_list, reference="WT")If you already have CellChat objects:
library(CellDiff)
# Load example data (pre-computed CellChat objects)
data(celllist) # Two conditions: NL and LS
data(cellchatlist) # Three conditions: WT, KO, DKO# Pathway ranking (two conditions)# Default: returns plot directlyplot<- rankDiff(object.list=celllist, comparison= c(1, 2))
# With full data access (v0.1.8)results<- rankDiff(object.list=celllist, comparison= c(1, 2), return.data=TRUE)
results$plot# The plotresults$data# Full data tableresults$top_paths# Top differential pathways# Compare ligand-receptor contributions
ContriDiff(object.list=celllist, signaling="TNF")
# Differential heatmaps
heatDiff(object.list=celllist, comparison= c(1, 2), measure="sender")
# Network visualizations
netDiff(object.list=celllist, comparison= c(1, 2), signaling="MIF")
# Pathway ranking with multi-condition support
rankDiffM(object.list=cellchatlist, reference="WT", show.all=TRUE)
# Comprehensive analysis wrapperresults<- compareCell(object.list=cellchatlist, reference="WT")For a comprehensive step-by-step tutorial, see the Getting Started vignette:
# View the tutorial in R
vignette("getting-started", package="CellDiff")
# Or browse vignettes
browseVignettes("CellDiff")The tutorial covers:
- Complete workflows from Seurat objects to results
- Understanding function parameters
- Interpreting visualizations
- Real-world analysis examples
- Troubleshooting common issues
- Customizing analyses for specific needs
Quick access to tutorial data:
# Load tutorial dataset
data(pbmc_tutorial)
# Explore the data
table(pbmc_tutorial$condition) # WT, KO, DKO
table(pbmc_tutorial$cell_type) # 5 cell types# Try the automatic workflowresults<- runCellChat(
seurat_object=pbmc_tutorial,
group.by="condition",
species="human",
run.analysis=TRUE,
reference="WT",
show_plots= c("barplot", "heatmap")
)
# View resultsresults$pathway_analysis$comparison_barplotresults$summaryFor detailed examples of all CellDiff functions, see the Multi-Condition Analysis vignette:
vignette("CellDiff", package="CellDiff")This vignette demonstrates:
- Advanced pathway ranking and visualization
- Customized heatmaps with specific pathways
- Ligand-receptor contribution analysis
- Finding common and unique patterns
- Network visualizations
- Global comparison of CellChat objects
Use runCellChat to automatically create CellChat objects from your Seurat object:
# Create CellChat objects onlycellchat_list<- runCellChat(
seurat_object=pbmc_tutorial,
group.by="condition", # Column in metadata with condition labelsspecies="human", # "human" or "mouse"cell.type.column="cell_type"# Column with cell type annotations
)
# Returns a named list of CellChat objectscellchat_list[["WT"]] # CellChat object for WT conditioncellchat_list[["KO"]] # CellChat object for KO condition# Then manually run CellDiff functions for differential analysis
rankDiffM(object.list=cellchat_list, reference="WT")
heatDiffM(object.list=cellchat_list, reference="WT")Choose which analyses to run with the show_plots parameter:
# Run specific analyses automaticallyresults<- runCellChat(
seurat_object=pbmc_tutorial,
group.by="condition",
species="human",
run.analysis=TRUE, # Run differential analysis automaticallyreference="WT", # Reference conditionshow_plots= c("barplot", "heatmap", "scatter") # Choose analyses
)
# Access resultsresults$cellchat_objects[["WT"]] # CellChat objectsresults$pathway_analysis# Always includedresults$heatmap# Only if "heatmap" in show_plotsresults$scatter# Only if "scatter" in show_plotsresults$summary# Always included# Run only pathway rankingresults<- runCellChat(
seurat_object=pbmc_tutorial,
group.by="condition",
species="human",
run.analysis=TRUE,
reference="WT",
show_plots= c("barplot") # Only rankDiffM
)
# Run all available analysesresults<- runCellChat(
seurat_object=pbmc_tutorial,
group.by="condition",
species="human",
run.analysis=TRUE,
reference="WT",
show_plots= c("barplot", "heatmap", "slope", "scatter", "network")
)Available analyses in show_plots:
"barplot"- Pathway ranking barplot (rankDiffM)"heatmap"- Differential heatmap (heatDiffM)"slope"- Pathway ranking slope plot (rankDiffM)"scatter"- Sender-receiver scatter plot (scatterDiff2DM)"network"- Network visualization (networkLRDiff)
runCellChat now exposes 39 parameters for complete control over CellChat analysis:
# Advanced customization with full CellChat parameter controlresults<- runCellChat(
seurat_object=pbmc_tutorial,
group.by="condition",
species="human",
# Data access (Seurat v4/v5 compatible)assay="RNA", # Use specific assay ("RNA", "SCT", etc.)slot.name="data", # Slot/layer to use# Database customizationdb.subset="Secreted Signaling", # Focus on specific interaction types# custom.db = my_custom_db, # Or use custom database# Communication probability parameterstype="truncatedMean", # Computation methodtrim=0.2, # Trim valuepopulation.size=FALSE, # Default: FALSE (matches CellChat)# Spatial data support (NEW!)distance.use=TRUE, # Use spatial distanceinteraction.range=500, # Interaction rangescale.distance=0.02, # Distance scalingcontact.dependent=TRUE, # Contact-dependent interactions# Preprocessing thresholds (v0.1.8: defaults now match CellChat)thresh=0.1, # Expression thresholdthresh.pc=0, # Default: 0 (matches CellChat)thresh.fc=0, # Default: 0 (matches CellChat)# Filtering parametersmin.cells=15, # Minimum cells per cell typerare.keep=TRUE, # Keep rare interactions# Network analysiscompute.centrality=TRUE, # Compute centrality metricsthresh.centrality=0.1, # Centrality threshold# Error handling (NEW!)stop.on.error=FALSE, # Continue if one condition failsverbose.cellchat=FALSE, # Suppress CellChat messages# Return options (NEW!)return.merged=TRUE, # Return merged objectsave.raw=TRUE# Save pre-aggregation objects
)
# Access different result componentsresults$cellchat_objects$WT# Individual CellChat objectresults$merged_cellchat# Merged object (if return.merged = TRUE)results$raw_cellchat_objects$WT# Pre-aggregation object (if save.raw = TRUE)Parameter Categories:
- Data Access:
assay,slot.name- Seurat v4/v5 compatible data extraction - Database:
db.subset,custom.db- Customize ligand-receptor database - Communication:
type,trim,population.size,raw.use- Probability computation - Spatial:
distance.use,interaction.range,scale.distance,contact.dependent- Spatial analysis - Preprocessing:
thresh,thresh.pc,thresh.fc- Gene expression thresholds - Filtering:
min.cells,min.samples,rare.keep,nonFilter.keep- Communication filtering - Network:
thresh.centrality,compute.centrality- Centrality analysis - Control:
stop.on.error,return.merged,save.raw,verbose,verbose.cellchat- Execution control
See ?runCellChat for complete parameter documentation.
If you already have CellChat objects, use compareCell for complete differential analysis:
# One-step comprehensive analysisresults<- compareCell(
object.list=cellchatlist,
reference="WT", # Reference conditioncell.type.strategy="union", # Handle missing cell typesshow.all=TRUE, # Show all pathways with significance indicatorsshow_plots= c("barplot", "heatmap", "scatter"), # Choose visualizationsverbose=TRUE# Show progress messages
)
# Access resultsresults$pathway_analysis$comparison_barplot# Main pathway comparison plotresults$pathway_analysis$all_significant_paths_full[["KO vs WT"]] # Significant pathwaysresults$heatmap# Detailed heatmapresults$scatter# Scatter plot analysisresults$summary# Summary statisticsresults$summary$significant_pathways_per_comparison# Count per comparison# The wrapper function automatically:# - Aligns cell types across conditions# - Runs rankDiffM, heatDiffM, scatterDiff2DM in sequence# - Organizes results with meaningful names# - Provides informative progress messages# - Generates summary statistics| Function | Purpose | Key Features |
|---|---|---|
runCellChat() | Create CellChat objects from Seurat | 39 parameters for complete CellChat control: data access, database customization, spatial support, advanced filtering, error handling, return options |
compareCell() | Comprehensive differential analysis | Automatic workflow: runs rankDiffM, heatDiffM, scatterDiff2DM, organizes results with summary statistics |
| Function | Purpose | Key Features |
|---|---|---|
rankDiffM() | Pathway ranking across conditions | show.all for all pathways, named list output, comparison-specific display |
heatDiffM() | Differential heatmaps | measure (count/weight/both), big_heatmap, custom colors |
scatterDiff2DM() | Sender-receiver scatter plots | Trajectory arrows, convex hulls, quadrant labels |
ContriDiffM() | L-R contribution analysis | Multiple comparison methods, custom pairs |
| Function | Purpose | Best For |
|---|---|---|
rankDiff() | Pathway ranking (2 conditions) | Simple pairwise comparison (use return.data = TRUE for full results) |
heatDiff() | Differential heatmap (2 conditions) | Visualizing sender/receiver changes |
scatterDiff() | Influence scatter plot | Overall signaling strength |
scatterDiff2D() | Sender-receiver scatter | Role changes between conditions |
ContriDiff() | L-R contribution (2 conditions) | Specific pathway analysis |
netDiff() | Network chord diagram | Visual network comparison |
networkLRDiff() | L-R network visualization | Detailed pathway networks |
| Function | Purpose |
|---|---|
findCommonUniquePatterns() | Identify shared/unique pathways with Venn diagrams and UpSet plots |
compareCellChatsM() | Timeline analysis of communication patterns |
alignCellTypes() | Handle missing cell types across conditions |
Comparison Methods:
all_vs_ref: Compare all conditions to a reference (most common)all_vs_all: All pairwise comparisonscustom_pairs: Specify exact comparisons
Cell Type Strategies:
shared: Only cell types present in all conditions (conservative)union: All cell types, fills missing with zeros (inclusive)
Visualization Options:
show.all: Show all pathways with fading for non-significant (rankDiffM)show_plots: Choose which plots to generate (wrapper functions)return_data: Return underlying data in addition to plots
CellDiff provides specialized functions for comparing cell-cell communication across more than two conditions. Let's assume we have a list of CellChat objects for three conditions: WT, KO, and DKO.
# First, create a named list of CellChat objectscellchatlist<- data("cellchatlist")
# Set WT as the referencereference<-1# Or use the name: reference = "WT"# Compare signaling pathway differences across all conditionspathway_results<- rankDiffM(
object.list=cellchatlist,
comparison_method="all_vs_ref", # Compare all conditions to the referencereference="WT", # Set WT as referencecell.type.strategy="union", # Use all cell types (fills missing with 0)use_log2fc=TRUE, # Use log2 fold change for better visualizationshow_comparison_barplot=TRUE, # Show faceted barplotshow_comparison_heatmap=TRUE, # Show heatmapshow_comparison_slope=TRUE, # Show slope plotshow.all=FALSE# Show only significant pathways per comparison (default)
)
# View different visualization typespathway_results$comparison_barplotpathway_results$comparison_heatmappathway_results$comparison_slope_plot# Get the top differential pathwaystop_pathways<-pathway_results$top_paths# Access results by comparison name (NEW!)pathway_results$all_significant_paths_full[["KO vs WT"]]
pathway_results$all_significant_paths_full[["DKO vs WT"]]
# Show all pathways with visual indicatorspathway_results_all<- rankDiffM(
object.list=cellchatlist,
comparison_method="all_vs_ref",
reference="WT",
cell.type.strategy="shared", # Use only common cell types (safer)show_comparison_barplot=TRUE,
show.all=TRUE# Show all pathways with fading and stars
)
# With show.all = TRUE:# - All pathways appear in all comparison panels# - Non-significant pathways are faded (alpha = 0.3)# - Significant pathways have stars (*p<0.05, **p<0.01, ***p<0.001)pathway_results_all$comparison_barplot# Use custom pairs for specific comparisonspathway_custom<- rankDiffM(
object.list=cellchatlist,
comparison_method="custom_pairs",
custom_comparisons=list(
c("WT", "KO"),
c("KO", "DKO"),
c("WT", "DKO")
),
show_comparison_barplot=TRUE,
show_comparison_heatmap=TRUE
)
# View custom comparison resultspathway_custom$comparison_barplot# Shows all custom pairspathway_custom$comparison_heatmap# Heatmap of custom comparisons# Create a multi-condition heatmap comparing sender signalingheatmap_result<- heatDiffM(
object.list=cellchatlist,
comparison= c(1, 2, 3), # Compare all three conditionsreference="WT", # Set WT as referencemeasure="sender", # Focus on sender signalinguse_log2fc=TRUE, # Use log2 fold changeshow_values=TRUE,
big_heatmap=TRUE,
color.heatmap= c("blue", "white", "red") # Custom colors
)
# The heatmap will display in RStudio automatically# To save to PDF:
pdf("heatmap_output.pdf", width=15, height=8)
ComplexHeatmap::draw(heatmap_result)
dev.off()# Compare specific condition pairs (e.g., WT vs KO, KO vs DKO, WT vs DKO)heatmap_custom<- heatDiffM(
object.list=cellchatlist,
comparison= c(1, 2, 3),
comparison_method="custom_pairs",
custom_comparisons=list(
c("WT", "KO"), # First comparison
c("KO", "DKO"), # Second comparison
c("WT", "DKO") # Third comparison
),
measure="sender",
use_log2fc=TRUE,
show_values=TRUE,
big_heatmap=TRUE,
color.heatmap= c("blue", "white", "red")
)# Compare sender-receiver roles across conditions#scatter_result <- scatterDiffM(# object.list = cellchatlist,# comparison = c(1, 2, 3), # Use all three conditions# reference = "WT", # Set WT as reference# comparison_method = "all_vs_ref", # Compare all to reference# show_group_labels = TRUE, # Show group labels# convex_hull = FALSE # Draw convex hulls around groups#)# For more detailed 2D visualizationscatter_result_2d<- scatterDiff2DM(
object.list=cellchatlist,
comparison= c(1, 2, 3), # Use all three conditionsreference="WT", # Set WT as referencecomparison_method="all_vs_ref", # Compare all to referenceshow.group.legend=TRUE, # Show legendconvex.hull=TRUE# Draw convex hull
)
scatter_result_2d<- scatterDiff2DM(
object.list=cellchatlist,
comparison= c(1, 2, 3), # Use all three conditionsreference="WT", # Set WT as referencecomparison_method="all_vs_ref", # Compare all to referenceshow.group.legend=TRUE, # Show legendconvex.hull=TRUE, # Draw convex hullshighlight.cells= c("Endo", "Mac", "ImmSC") # Highlight specific cell types
)# Compare L-R pair contributions for the WNT pathway across conditionslr_result<- ContriDiffM(
object.list=cellchatlist,
signaling="WNT",
reference="WT",
stack.method="side-by-side", # Display conditions side by sideshow.heatmap=TRUE, # Show heatmap visualizationtop.n=10# Limit to top 10 L-R pairs
)
# The function returns a list of plotslr_result$barplotlr_result$heatmap# Use custom pairs for L-R contribution analysislr_custom<- ContriDiffM(
object.list=cellchatlist,
signaling="WNT",
comparison_method="custom_pairs",
custom_comparisons=list(
c("WT", "KO"),
c("KO", "DKO")
),
show.heatmap=TRUE,
top.n=10
)# Identify signaling patterns that are common or unique across conditions# With comprehensive visualizationspatterns<- findCommonUniquePatterns(
object.list=cellchatlist,
comparison= c(1, 2, 3), # Compare all three conditionsmin_overlap=2, # Minimum number of conditions to consider a pattern commonshow.venn=TRUE, # Show Venn diagram (default)show.upset=TRUE, # Show UpSet plotshow.barplot=TRUE, # Show pattern count barplotshow.network=TRUE, # Show network visualizationreturn_networks=TRUE, # Return full network datareturn.data=TRUE, # Return underlying datatop.n=20# Top 20 patterns for network
)
# Examine common patterns across conditions
head(patterns$common_patterns)
# Examine unique patterns for each condition
head(patterns$unique_patterns)
# View visualizationspatterns$plots$venn# Venn diagram showing overlapspatterns$plots$upset# UpSet plot for complex intersectionspatterns$plots$barplot# Pattern counts per conditionpatterns$plots$network_graph# Network of top interactions# Access the VennDetail object for further analysisvenn_obj<-patterns$plots$venn_object# Compare multiple CellChat objects to identify global changesglobal_comparison<- compareCellChatsM(
object.list=cellchatlist,
comparison= c(1, 2, 3), # Compare all three conditionsreference="WT", # Set WT as referencemeasure.type="sender", # Focus on sender signalingnorm.method="z-score", # Normalize with z-scoreshow.pathway=TRUE, # Show pathway contributionsshow.heatmap=TRUE, # Generate heatmap (ComplexHeatmap)label.timeline=TRUE, # Add labels to timelinelabel.pathway=TRUE, # Add labels to pathway plotlabel.top=5, # Label top 5 per conditionreturn.data=TRUE# Return underlying data
)
# View the resultsglobal_comparison$timeline# Timeline plot of signaling changesglobal_comparison$pathway# Pathway contribution changesglobal_comparison$heatmap# ComplexHeatmap with cell type annotations# Access the underlying dataglobal_comparison$data$scores# Signaling scores per conditionglobal_comparison$data$celltype_colors# Consistent color scheme# Visualize network differences for a specific pathwaynet_diff<- netDiff(
object.list=cellchatlist,
comparison= c(1, 2), # Compare first two conditionssignaling="WNT", # Focus on WNT signalinguse_normalized=TRUE, # Normalize networks before comparisoncolor.use= c("darkorange", "deepskyblue"), # Custom colorshighlight_sources= c("Tcell", "Bcell") # Highlight specific sources
)
# Integrated network visualization showing pathways, cells, and LR pairsnetwork_viz<- networkLRDiff(
object.list=cellchatlist,
comparison= c(1, 2), # Compare first two conditionspathways=top_pathways[1:3], # Use top differential pathwaysnode.size.factor=1.2, # Larger nodesedge.width.factor=1.5, # Thicker edgeslabel.cell=TRUE, # Label cell typesnode.label.repel=TRUE# Avoid label overlaps
)# Create a custom heatmap with specific pathwayscustom_heatmap<- heatDiffM(
object.list=cellchatlist,
comparison= c(1, 2, 3),
reference="WT",
measure="both", # Both sender and receiversignaling=top_pathways, # Use top differential pathwaystranspose=TRUE, # Transpose the heatmapuse_log2fc=TRUE, # Use log2 fold changecolor.heatmap= c("purple", "white", "green"), # Custom colorscluster_rows=TRUE, # Cluster rowscluster_cols=TRUE, # Cluster columnsshow_values=TRUE, # Show values in cellsvalue_digits=1, # 1 decimal placeshow.heatmap_border=TRUE, # Show borderssave_plot=TRUE, # Save the plotsave_name="custom_heatmap.pdf"# Filename
)For large datasets with many cell types or pathways, CellDiff provides options to filter and focus on the most relevant information:
# Filter to include only significant pathwaysfiltered_results<- rankDiffM(
object.list=cellchatlist,
pThresh=0.01, # Stricter p-value thresholdfilter_min_change=0.5, # Higher fold change thresholdtop.n=15# Limit to top 15 pathways
)
# Filter specific cell types for visualizationspecific_heatmap<- heatDiffM(
object.list=cellchatlist,
filter_zeros=TRUE, # Filter out pathways with no signalfilter_thresh=0.1# Minimum signal threshold
)# Get detailed information about differential pathwayspathway_data<- rankDiffM(
object.list=cellchatlist,
comparison_method="all_vs_ref",
reference="WT",
return_top_paths=TRUE,
return_data=TRUE
)
# Extract detailed informationpathway_stats<-pathway_data$datasignificant_paths<-pathway_data$all_significant_paths# Print statistics for top pathways
print(pathway_stats[pathway_stats$name%in%pathway_data$top_paths, ])# Analyze how cell types change their rolesrole_changes<- scatterDiff2DM(
object.list=cellchatlist,
comparison_method="all_vs_ref",
reference="WT",
return_data=TRUE
)
# Examine cells with the largest changesarrows_data<-role_changes$arrowstop_changes<-arrows_data[order(arrows_data$total_change, decreasing=TRUE), ]
head(top_changes)
# Identify cells that change quadrants (e.g., from sender to receiver)quadrant_changes<-arrows_data[arrows_data$quadrant%in% c("II", "IV"), ]
print(quadrant_changes)Use the cell.type.strategy parameter:
# Use only cell types present in ALL conditions (safer, recommended)
rankDiffM(object.list=cellchatlist, cell.type.strategy="shared")
# Use ALL cell types from any condition (fills missing with 0)
rankDiffM(object.list=cellchatlist, cell.type.strategy="union")The function will report which cell types are missing and how many:
Using union strategy: 10 cell types aligned
- 8 cell types present in all objects
- 2 cell types present in some objects (will use 0 for missing)
All output lists now have meaningful names:
results<- rankDiffM(object.list=cellchatlist, reference="WT")
# Old way (still works)results$all_significant_paths_full[[1]]
# New way (clearer!)results$all_significant_paths_full[["KO vs WT"]]
results$all_significant_paths_full[["DKO vs WT"]]
# See all comparison names
names(results$all_significant_paths_full)Use the show.all parameter in rankDiffM:
# Default: Only show pathways significant in each specific comparisonresults<- rankDiffM(object.list=cellchatlist, show.all=FALSE)
# Show all pathways with visual indicatorsresults<- rankDiffM(object.list=cellchatlist, show.all=TRUE)With show.all = TRUE:
- All pathways appear in all comparison panels
- Non-significant pathways are faded (alpha = 0.3)
- Significant pathways are opaque with stars (*p<0.05, **p<0.01, ***p<0.001)
- A subtitle explains the visualization
# Enable debug mode (package-wide)
options(CellDiff.debug=TRUE)
# Run your analysis - will show debug outputresults<- rankDiffM(object.list=cellchatlist, show.all=TRUE)
# Disable debug mode
options(CellDiff.debug=FALSE)For multiple group comparisons, you can specify a reference using either the index or name:
# By index (position in the list)
rankDiffM(object.list=cellchatlist, reference=1)
# By name (if your list has named elements)
rankDiffM(object.list=cellchatlist, reference="WT")Use the comparison parameter to select specific conditions:
# Compare only WT and DKO (assuming positions 1 and 3)
heatDiffM(object.list=cellchatlist, comparison= c(1, 3))
# Or by name
heatDiffM(object.list=cellchatlist, comparison= c("WT", "DKO"))# Use rankDiffM and extract top pathwaysresults<- rankDiffM(object.list=cellchatlist)
top_paths<-results$top_pathsMany functions have a return_data = TRUE option that provides the underlying data:
# Get data for further processingheatmap_data<- heatDiffM(object.list=cellchatlist, return_data=TRUE)
write.csv(heatmap_data$diff_matrix, "differential_heatmap_data.csv")For questions or issues, please contact: guokai8@gmail.com
Create an issue on the GitHub repository: https://github.com/guokai8/CellDiff/issues