Skampak
Skampak

Reputation: 35

R visNetwork: create new type of edges

I want to create a PAG(parental ancestral graph) with visNetwork for my shiny app. In order to do that i have to create edges that have both circles and arrows. According to the visNetwork package i can convert the arrows to circles like this

visNetwork(nodes, edges) %>% 
  visEdges(arrows = list(to = list(enabled = TRUE, 
     scaleFactor = 2, type = 'circle')))

But i want to have both an arrow and a circle, or two circles in one edge like in this picture PAG

The arrows.from.type and arrows.to.type seem to be working but i now i have this problem. I want to draw this graph according to an adjacency matrix So i have this code

  i = 1
  j = 1
  for(i in i:ncol(results))
  {
    j = i
    for(j in j:nrow(results))
    {
      if(results[j,i]==1)
      {
        dashBoard = c(dashBoard,TRUE)
        colorBoard = c(colorBoard, "green")
        if(results[i,j]==1)
        {
          fromtest <- c(fromtest,Cnames[i])
          totest <- c(totest,Rnames[j])
          arrfrom <-c(arrfrom,"circle")
          arrto<-c(arrto,"circle")
        }
        else if(results[i,j]==2)
        {

          fromtest<-c(fromtest,Cnames[i])
          totest<-c(totest,Rnames[j])
          arrfrom <-c(arrfrom,"circle")
          arrto<-c(arrto,"arrow")
        }}

That goes on for every possible combination except 1,1 and 1,2 In the end the edges are printed like that

edgesprint <-data.frame(from = fromtest,
                          to = totest,
                          arrows.from.type=arrfrom,
                          arrows.to.type=arrto,
                          dashes = dashBoard,
                          physics = FALSE,
                          smooth = FALSE,
                          width = 3,
                          shadow = TRUE,
                          color = list(color = colorBoard, highlight =   "red", hover = "green"),
                          links = links)

This method works good but sometimes without changing any code i get this error

error in data.frame arguments imply differing number of rows

Upvotes: 0

Views: 1034

Answers (1)

Simon Larsen
Simon Larsen

Reputation: 742

You can set individual arrow types in the edges data frame by adding columns arrows.to.type and arrows.from.type:

library(visNetwork)
library(magrittr)

nodes <- data.frame(id=c("a","b","c","d"), label=c("a","b","c","d"))
edges <- data.frame(
  from = c("a","a","a"),
  to = c("b","c","d"),
  arrows.from.type = c(NA,"circle","circle"),
  arrows.to.type = c("arrow","circle",NA)
)

visNetwork(nodes, edges)

Result:

Resulting network

This approach works for all other attributes you can set through visNodes and visEdges. See here for an example.

Upvotes: 1

Related Questions