You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在igraph绘图中保留SOI节点,仅对非SOI节点应用权重阈值?

Modified R igraph Function to Keep SOI Nodes

I get it—your current function filters all edges by weight, which can accidentally drop SOI nodes if they end up with no remaining connections. The fix is to ensure we always retain all SOI nodes, even if they’re isolated, while still applying the weight threshold only to non-SOI nodes (i.e., non-SOI nodes are only kept if they have edges meeting the threshold).

Here’s the updated graph_rel_network function with comments explaining the key changes:

library(igraph)

graph_rel_network <- function(rel.matrix, all_nodes, soi, threshold = 0.5) {
  # Convert the relation matrix to a long-format edge list
  edges <- as.data.frame(as.table(rel.matrix))
  colnames(edges) <- c("from", "to", "weight")
  
  # Filter edges to keep only those above the weight threshold
  filtered_edges <- edges[edges$weight > threshold, ]
  
  # Get all nodes that appear in the filtered edges (non-SOI nodes that meet the threshold)
  edge_nodes <- unique(c(filtered_edges$from, filtered_edges$to))
  
  # Combine SOI nodes with edge nodes to ensure all SOI nodes are included, even if isolated
  final_vertices <- union(soi, edge_nodes)
  
  # Create the graph: use filtered edges, and ensure all final vertices are included
  g <- graph_from_data_frame(
    d = filtered_edges,
    directed = FALSE,  # Adjust to TRUE if your graph is directed
    vertices = final_vertices
  )
  
  # Optional: Customize plotting to highlight SOI nodes (e.g., different color/size)
  V(g)$color <- ifelse(V(g)$name %in% soi, "lightblue", "lightgray")
  V(g)$size <- ifelse(V(g)$name %in% soi, 12, 8)
  
  # Plot the graph
  plot(g, vertex.label.cex = 1.2, edge.width = E(g)$weight * 2)
  
  return(g)
}

Key Changes Explained:

  • Retain SOI Nodes: We explicitly combine the SOI nodes with any non-SOI nodes that made it through the edge filter using union(soi, edge_nodes). This guarantees every SOI node is in the graph, even if they have no edges left after thresholding.
  • Threshold Application: The edge filter still removes edges below the threshold, but non-SOI nodes only stay in the graph if they’re part of at least one filtered edge.
  • Visual Highlighting: Added optional code to make SOI nodes stand out (light blue color, larger size) so you can easily verify they’re included.

Test with Your Example:

If you run this with soi = c("A", "I", "G"), even if node G has no edges above the threshold, it will still appear as an isolated light blue node in the plot instead of being omitted entirely.

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:58:16