R:从矩阵添加图形标签

wbrvyc0a  于 2023-05-04  发布在  其他
关注(0)|答案(2)|浏览(81)

我正在使用R编程语言。
我有以下网络图:

library(tidyverse)
library(visNetwork)
library(htmlwidgets)

set.seed(123)
mat <- matrix(runif(19*20), nrow = 19, ncol = 20)
mat <- t(apply(mat, 1, function(x) x/sum(x)))
mat <- rbind(mat, c(rep(0, 19), 1))

nodes <- data.frame(id = 1:20)
edges <- data.frame(from = sample(1:20, 100, replace = TRUE), to = sample(1:20, 100, replace = TRUE))

nodes$shape <- 'circle'
edges$weight <- apply(edges, 1, function(x) mat[x["from"], x["to"]])

nodes$shape <- 'circle'

# create the network graph
network <- visNetwork(nodes, edges) %>%
  visEdges(arrows = list(to = list(enabled = TRUE))) %>%
  visIgraphLayout(layout = "layout_in_circle") 
network

我的问题现在,我想给这个网络添加“边标签”(基于权重列):

from to      weight
1    6 11 0.061566284
2   10 12 0.078716949
3   10  8 0.001003639
4    6 18 0.044656020
5   16  5 0.061479305
6   16 18 0.060615245

我在这里找到了这个链接,并一直在尝试从这里修改代码来添加标签:https://datastorm-open.github.io/visNetwork/edges.html
但我在这样做时遇到了麻烦-我尝试了以下代码,但没有显示标签:

network <- visNetwork(nodes, edges) %>%
    visEdges(arrows = list(to = list(enabled = TRUE)), label = list(enabled = TRUE)) %>%
    visIgraphLayout(layout = "layout_in_circle") 
network

有人能告诉我怎么修吗?
谢谢!

e5nqia27

e5nqia271#

我想我可能在以前的文章中回答了你的问题:R:理解同一语句中的双重列表
请执行以下操作:

edges$weight <- apply(edges, 1, function(x) mat[x["from"], x["to"]])

并将其更改为:

edges$label <- as.character(apply(edges, 1, function(x) mat[x["from"], x["to"]]))

edges Dataframe 需要有一个label变量,该变量是字符,而不是数字。

jslywgbw

jslywgbw2#

使用Jay Achar提供的答案的完整代码(如果有人想从开始到结束复制/粘贴):

library(tidyverse)
 library(visNetwork)
 library(htmlwidgets)

 set.seed(123)
 mat <- matrix(runif(19*20), nrow = 19, ncol = 20)
 mat <- t(apply(mat, 1, function(x) x/sum(x)))
 mat <- rbind(mat, c(rep(0, 19), 1))
 
 
 nodes <- data.frame(id = 1:20)
 edges <- data.frame(from = sample(1:20, 100, replace = TRUE), to = sample(1:20, 100, replace = TRUE))
 
 nodes$shape <- 'circle'
 edges$weight <- apply(edges, 1, function(x) mat[x["from"], x["to"]])
 
 nodes$shape <- 'circle'
 edges$weight <- apply(edges, 1, function(x) mat[x["from"], x["to"]])
 edges$label <- as.character(apply(edges, 1, function(x) mat[x["from"], x["to"]]))
 

 nodes$label = paste("Node", 1:20)
 
 
 network <- visNetwork(nodes, edges) %>%
     visEdges(arrows = list(to = list(enabled = TRUE))) %>%
     visIgraphLayout(layout = "layout_in_circle") 
 
 network

相关问题