代码之家  ›  专栏  ›  技术社区  ›  J Bock

NetworkD3 Sankey Plot in R:如何仅将文本标签从内部节点的右侧切换到左侧

  •  1
  • J Bock  · 技术社区  · 7 年前

    Sankey Plot Example

    我对Sankey使用了以下代码:

    sankeyNetwork(Links = SankeyLinks, Nodes = SankeyNodes, Source = "source",
              Target = "target", Value = "value", NodeID = "names", 
              fontSize = 14, nodeWidth = 20,nodePadding = 15,NodeGroup = "nodeColor",
              colourScale = JS(ColourScale), LinkGroup = "linkColor",
              sinksRight = T)
    

    左侧 内部节点的 没有 更改开始节点和叶节点上的文本位置(分别为右侧和左侧)。

    我研究了一个类似的问题: Place text values to right of sankey diagram

    How to place node title to the left or right of the node in d3 Sankey graph?

    答案是在D3.js中编码的,我还没有学会,也不知道如何在我的R代码中实现,或者他们正在将文本标签移动到节点的右侧。

    如果我能在R中实现任何将内部节点的文本移到左侧的建议,我将不胜感激!

    编辑:当我使用集合时,使用注释中给出的示例代码。种子它不会创建内部节点,所以这可能就是问题所在? Output Example

    2 回复  |  直到 7 年前
        1
  •  3
  •   CJ Yetman    7 年前

    从@timelyportfolio开始 answer ,您可以修改它以在应用格式之前过滤到任何节点子集。。。

    library(networkD3)
    library(htmlwidgets)
    
    links <- data.frame(
      src = c(0,0,1,1,2,2,3,3,4,4,5,5,6),
      target = c(3,6,4,5,5,6,7,9,8,9,7,10,7),
      value = 1
    )
    
    nodes <- data.frame(name = c(1, 2, 3,
                                 "Middle 1", "Middle 2", "Middle 3", "Middle 4", 
                                 4,5,6,7))
    
    sn <- sankeyNetwork(
      Links=links, Nodes=nodes, Source='src', Target='target',
      Value='value', NodeID='name', fontSize=16,
      width=600, height=300,
      margin = list("left"=100)
    )
    
    sn
    
    sn <- onRender(
      sn,
      '
      function(el,x){
      // select all our node text
      d3.select(el)
      .selectAll(".node text")
      .filter(function(d) { return d.name.startsWith("Middle"); })
      .attr("x", x.options.nodeWidth - 16)
      .attr("text-anchor", "end");
      }
      '
    )
    
    sn$jsHooks$render[[1]]
    # $code
    # [1] "\n  function(el,x){\n  // select all our node text\n  d3.select(el)\n  .selectAll(\".node text\")\n  .filter(function(d) { return d.name.startsWith(\"Middle\"); })\n  .attr(\"x\", x.options.nodeWidth - 16)\n  .attr(\"text-anchor\", \"end\");\n  }\n  "
    # 
    # $data
    # NULL
    
    sn
    

    enter image description here

        2
  •  2
  •   Omar Abd El-Naser    7 年前

      .filter(function(d) { return d.name.startsWith("Middle"); })
    

    以下是我所做的使其生效

    onRender(
            sn,
            paste0('
            function(el,x){
            d3.select(el)
            .selectAll(".node text")
            .filter(function(d) { return (["',paste0(Middle,collapse = '","'),'"].indexOf(d.name) > -1);})
            .attr("x", 6 + x.options.nodeWidth)
            .attr("text-anchor", "end");
            }
            ')
    )
    

    我没有使用 startsWith() 功能和使用 indexOf() ,中间是R中的一个变量,即,

    Middle <- c("Middle 1","Middle 2","Middle 3","Middle 4")