R networkD3 color node stroke for radialNetwork()

旧时模样 提交于 2019-12-30 11:09:20

问题


The networkd3 package contains some very nice functions for creating the obvious networks. Different functions have different arguments, so this questions is specifically in regards to the radialNetwork() function. Is it possible to have the color of the node stroke change according to a given vector?

The below code creates a the network graph but changing the argument for the node stroke to a vector containing different colors does not work.

library(networkD3)
library(tidyverse)
library(data.tree)

## Data
input <- list(number=50)
Data_tree <- data.frame(Start="Class",
                      Asset = sample(c("FI","Equity","Currency","Commodities"),input$number,replace = TRUE),
                      Sub_Asset = sample(c("Asia","Europe","USA","Africa","ME"),input$number,replace = TRUE),
                      Ticker = replicate(input$number,paste0(sample(LETTERS,3),collapse=""))) %>% 
unite(col="pathString",Start,Asset,Sub_Asset,Ticker,sep="-",remove=FALSE) %>%
select(-Start) %>% as.Node(pathDelimiter = "-")



radialNetwork(ToListExplicit(Data_tree, unname = TRUE ), 
           linkColour = "#ccc",
           nodeColour = "#fff",
           nodeStroke = "orange",
           textColour = "#cccccc")


回答1:


Not directly... networkd3 does not support that capability. However, you can inject your own JavaScript into that attribute.

For example, if you have a vector of color names in the proper order, you could convert that to a JavaScript array (in the form: ["red", "blue", "green"]) and use the JS function from the htmlwidget package to build a function to pass through the nodeStroke argument.

colorVector <- c("black", "red", "blue", "green", "orange", 
    rep("red", 5), rep("blue", 5), rep("green", 4), rep("orange", 4),
    rep("red", 11), rep("blue", 14), rep("green", 14), rep("orange", 11))

jsarray <- paste0('["', paste(colorVector, collapse = '", "'), '"]')
nodeStrokeJS <- JS(paste0('function(d, i) { return ', jsarray, '[i]; }'))

radialNetwork(ToListExplicit(Data_tree, unname = TRUE ), 
    linkColour = "#ccc",
    nodeColour = "#fff",
    nodeStroke = nodeStrokeJS,
    textColour = "#cccccc")


来源:https://stackoverflow.com/questions/42568997/r-networkd3-color-node-stroke-for-radialnetwork

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!