Search code examples
rvisnetwork

Color nodes differently and remove label in visNetwork


Trying to visualize a network in R, I have an edges and nodes list. Nodes list looks like this - "id", "label" and "type":

nodes

I would like to color the nodes according to their type. So far I tried this by embedding the if statement, but this does not seem to work.

visNetwork(nodes, edges) %>% 
  visIgraphLayout(layout = "layout_in_circle") %>% 
  visNodes(label = NULL,(
    if (nodes$type ="gimn") { 
      color= "slategrey"
    } else if (nodes$type ="szakgimn") {
      color="pink"
    } else if  (nodes$type ="ált_isk") {
      color="black"
    } else {
      color ="tomato"
    })) %>% 
  visEdges(arrows = "middle")

How to assign color to the nodes according to their type? Also how to remove labels from the plot? (The code above did not seem to work for that either.)


Solution

  • I guess you can try a nested ifelse to define colors based on type like below

    visNetwork(nodes, edges) %>%
      visIgraphLayout(layout = "layout_in_circle") %>%
      visNodes(
        label = NULL,
        color = ifelse(nodes$type == "gimn",
          "slategrey",
          ifelse(nodes$type == "szakgimn",
            "pink",
            ifelse(nodes$type == "alt_isk",
              "black", "tomato"
            )
          )
        )
      ) %>%
      visEdges(arrows = "middle")
    

    Another way is to add color to nodes before using pipes, e.g.,

    nodes$color <- ifelse(nodes$type == "gimn",
              "slategrey",
              ifelse(nodes$type == "szakgimn",
                "pink",
                ifelse(nodes$type == "alt_isk",
                  "black", "tomato"
                )
              )
            )
    visNetwork(nodes, edges) %>%
          visIgraphLayout(layout = "layout_in_circle") %>%
          visEdges(arrows = "middle")