2

I am working with the R programming language.

I generated this random network graph and matrix:

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"]])

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

enter image description here

Now, I am trying to add the labels (i.e. the decimal numbers) from this matrix to each corresponding edge on this graph (i.e. edges$weight)

I found these two previous posts (Integrating the js code in R to make the visNetwork edges curved, Create a visNetwork diagram where edge labels do not overlap) - but I am not sure how to adapt the code here to suit my problem.

Can someone please show me how to do this?

Thanks!

stats_noob
  • 5,401
  • 4
  • 27
  • 83

1 Answers1

1

Here is how we could do it, see here https://www.quantargo.com/help/r/latest/packages/visNetwork/2.0.9/visNetwork

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, 
                    label = paste("Node", 1:20))

edges <- data.frame(from = sample(1:20, 100, replace = TRUE), 
                    to = sample(1:20, 100, replace = TRUE),
                    label = paste("Edge", 1:100))                          

nodes$shape <- 'circle'

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

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66
  • @ TarJae: Thank you so much for your answer! I am trying to get the labels from "mat" (i.e. decimal numbers) to appear on the corresponding network edges. do you know how to do this? thank you so much! – stats_noob Apr 28 '23 at 02:31