【问题标题】:border each node in a network created using networkD3::forceNetwork() with a specific color使用特定颜色为使用 networkD3::forceNetwork() 创建的网络中的每个节点设置边界
【发布时间】:2020-02-16 21:51:46
【问题描述】:

考虑以下网络,是否可以使用 中的 forceNetwork 函数基于 MisNodes 数据框中的列用颜色为节点设置边界。它可以选择为边缘着色,但不能为节点边界着色。

library(networkD3) 

# Load data
data(MisLinks)
data(MisNodes)

# Plot
forceNetwork(Links = MisLinks, Nodes = MisNodes,
            Source = "source", Target = "target",
            Value = "value", NodeID = "name",
            Group = "group", opacity = 0.8)

【问题讨论】:

    标签: networkd3 r d3.js htmlwidgets networkd3


    【解决方案1】:

    假设您的节点数据框有一列包含有效的颜色值,您可以预先添加自定义 JavaScript 来设置节点边框颜色...

    library(networkD3)
    library(htmlwidgets)
    
    # Load data
    data(MisLinks)
    data(MisNodes)
    
    MisNodes$border <- c(rep("#F00", 20), rep("#0F0", 20), rep("#00F", 20), rep("#F00", 17))
    
    
    # Plot
    fn <- forceNetwork(Links = MisLinks, Nodes = MisNodes,
                 Source = "source", Target = "target",
                 Value = "value", NodeID = "name",
                 Group = "group", opacity = 0.8)
    
    
    # add the color column back in to the data in the htmlwidget because
    # forceNetwork only passes through the necessary columns
    fn$x$nodes$border <- MisNodes$border
    
    
    # add custom JavaScript to set the node stroke to the color in the border column
    fn <- htmlwidgets::onRender(fn, 
      'function(el, x) { d3.selectAll("circle").style("stroke", d => d.border); }')
    
    
    # display
    fn
    

    【讨论】:

    • 感谢您的宝贵时间。我的解决方法略有不同。我已经分叉了您的包并为 forceNetwork() 提供了一个可选参数(用户可以在其中提供颜色作为 MisNodes df 的列或所有节点的单一颜色代码),并且还对相应的 js 文件进行了更改。但是,它以这种方式为节点边界着色,但是当我尝试使用相同的方法为节点填充颜色时,它不起作用。在那种情况下,我不得不使用 colourScale 参数 colourScale = JS('d3.scaleOrdinal().domain(["g1", "g2", "g3"]).range(["#666", "#F3C", "#FF3"]);').
    猜你喜欢
    • 2016-04-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多