Hands‐On Example - iffatAGheyas/bioinformatics-tutorial-wiki GitHub Wiki
6.3.8 Hands-On Example – Co-Expression Network in R & Cytoscape
In this mini-tutorial you’ll:
- Simulate a small gene expression matrix.
- Compute pairwise Pearson correlations.
- Threshold to define edges.
- Build an igraph network and export edge/node tables.
- Import into Cytoscape for visualization.
A. R Code
# 1. Install & load packages
# install.packages(c("igraph","WGCNA"))
# BiocManager::install("RCy3")
library(igraph)
library(WGCNA) # for network utilities
# library(RCy3) # optional, for programmatic Cytoscape control
# 2. Simulate expression: 50 genes × 20 samples
set.seed(123)
nGenes <- 50
nSamples <- 20
expr <- matrix(rnorm(nGenes * nSamples), nrow = nGenes, ncol = nSamples)
rownames(expr) <- paste0("Gene", sprintf("%02d", 1:nGenes))
colnames(expr) <- paste0("Sample", 1:nSamples)
# 3. Compute Pearson correlation matrix (genes × genes)
corrMat <- cor(t(expr))
# 4. Threshold correlations to define edges (e.g. |r| ≥ 0.8)
thresh <- 0.8
adjMat <- corrMat
adjMat[abs(adjMat) < thresh] <- 0
diag(adjMat) <- 0
# 5. Build igraph object
g <- graph_from_adjacency_matrix(adjMat, mode = "undirected", weighted = TRUE)
# 6. Export edge list (for Cytoscape import)
edges <- as_data_frame(g, what = "edges")
write.csv(edges, "network_edges.csv", row.names = FALSE)
# 7. Export node table with degree (optional attributes)
nodes <- data.frame(
id = V(g)$name,
degree = degree(g)
)
write.csv(nodes, "network_nodes.csv", row.names = FALSE)
# 8. (Optional) Quick plot in R
plot(
g,
vertex.label.cex = 0.7,
vertex.size = V(g)$degree + 2,
edge.width = E(g)$weight * 2,
main = "Co-Expression Network (r ≥ 0.8)"
)
-
Files generated:
-
network_edges.csv (columns: from,to,weight)
-
network_nodes.csv (columns: id,degree)
-
B. Visualize in Cytoscape
-
Launch Cytoscape
Download/install from https://cytoscape.org if needed. -
Import Network
- File → Import → Network → From Table (Text/MS Excel)
- Select
network_edges.csv
, set:- Source Interaction = from
- Target Interaction = to
- Edge Attribute = weight
- Click Import
-
Import Node Attributes
- File → Import → Table → From File…
- Select
network_nodes.csv
, choose:- Key Column For Network = id
- Table Contains = Node Table
-
Style & Layout
- Layout → Prefuse Force Directed (or “yFiles Organic”) to arrange nodes
- Style → Node Size mapped to degree (larger nodes = higher connectivity)
- Style → Edge Width mapped to weight (thicker edges = stronger correlation)
- Style → Node Label = id; adjust font size as needed
-
Export Figure
- File → Export → Network View as Graphics…
- Choose PDF, SVG, or PNG at desired resolution
Tip: You can also automate Cytoscape from R via the RCy3 package to script import, layout, and styling steps—run Cytoscape with the REST API enabled.