【问题标题】:Change node colors in d3 Sankey Diagram based on additional column in data根据数据中的附加列更改 d3 Sankey 图中的节点颜色
【发布时间】:2016-10-23 02:42:54
【问题描述】:

我正在使用 D3 Sankey 插件创建一个 Sankey 图。我有标准列:源、目标、值加上一个名为 nodeColor 的附加列。我希望目标节点的颜色由“nodeColorTarget”列中记录的颜色决定。我能够将节点的源代码更改为全一种颜色。但是,我无法开发一个函数来使用附加列来指示颜色。

样本数据:

source,target,value,nodeColorTarget
Dist A,Place1,1,red
DistB,Place1,5,red
DistB,Place2,2,grey
DistB,Place2,1,grey
DistB,Place3,2,blue

现有代码:

// add the rectangles for the nodes
  node.append("rect")
      .attr("height", function(d) { return d.dy; })
      .attr("width", sankey.nodeWidth())
      .style("fill", "red") 
      //.style("fill", function(d) { 
          //return d.color = color(d.name.replace(/ .*/, "")); })
      //.style("stroke", function(d) { 
         // return d3.rgb(d.color).darker(2); })
    //.append("title")
     // .text(function(d) { 
         // return d.name + "\n" + format(d.value); });

我的完整代码是here

【问题讨论】:

  • 我更新了答案

标签: javascript d3.js colors sankey-diagram


【解决方案1】:

你首先需要添加这样的属性:

graph.nodes.push({ "name": d.source, "color": d.nodeColorTarget });

那你可以这样称呼它:

.style("fill", function(d) { return d.color;}) 

看这个例子:http://plnkr.co/edit/4xPx05PxnWxoQBhIj2lo?p=preview

PS : 随着数据结构的变化,我做了一些小改动

【讨论】:

  • 在您提供的示例中,我看到颜色发生了变化。但是,图表不再正确。现在它们散布在左边,而不是让源在左边,目标在右边。例如,您在右侧看到 DisB。此外,DistB 和 Place3 之间没有流向箭头。右下角还有一堆空节点。关于如何解决这个问题的任何想法?
  • 修好了,我忘了删除重复的,看更新的小提琴plnkr.co/edit/4xPx05PxnWxoQBhIj2lo?p=preview
  • 谢谢你的作品。我调整了您的回复,以包含需要修改的代码的特定 sn-ps。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 2022-06-10
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多