如何实现 D3 比例让孩子继承父母的颜色并带有刻度?

2024-02-25

我有一个 D3.js 树,它对节点和链接应用了不同的颜色。

颜色是硬编码的:

nodeUpdate.select("circle")
      .attr("r", 10)
       .style("fill", function(d) { 
     if(d.name == "Top Level") {
      return d._children ? "blue" : "#fff"; 
      }
    if(d.name == "Second A") {
     return d._children ? "red" : "#fff"; 
    }
      if(d.name == "Second B") {
      return d._children ? "green" : "#fff"; 
      }
    if(d.name == "Second C") {
      return d._children ? "purple" : "#fff"; 
      }
      if(d.name == "Second D") {
      return d._children ? "gold" : "#fff"; 
      }
    })
     .style("stroke", function(d) { 
     if(d.name == "Top Level") {
      return "blue"; 
      }
    if(d.name == "Second A") {
     return "red"; 
    }
      if(d.name == "Second B") {
      return "green"; 
      }
    if(d.name == "Second C") {
      return "purple"; 
      }
      if(d.name == "Second D") {
      return "gold"; 
      }
    });

and

link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("stroke-width", function(d){
        return 1;
      })
      .attr("d", function(d) {
        var o = {x: source.x0, y: source.y0};
        return diagonal({source: o, target: o});
      })
    .style("stroke", function(d) {
      return linkColor(d.target.name);
    });

and

function linkColor(node_name) {
    switch (node_name)
    {
      case 'Second A': case 'Third A':  case 'Third B': 
        return 'red';
        break;
      case 'Second B': case 'Third C':  case 'Third D': 
        return 'green';
        break;
      case 'Second C': case 'Third E':  case 'Third F': 
        return 'purple';
        break;
      case 'Second D': case 'Third G':  case 'Third H': 
        return 'gold';
    }
}

See fiddle https://jsfiddle.net/f5tpy1db/2/

我不想对每个节点和链接的颜色进行硬编码,而是想实现d3-scale https://github.com/d3/d3-scale为节点和线条着色。解决方案是让孩子们“继承”父母的颜色那种颜色的毕业 https://github.com/d3/d3-scale-chromatic/blob/master/README.md#schemeYlGnBu自动给出 x 个孩子。

https://www.d3indepth.com/scales/ https://www.d3indepth.com/scales/

我怎样才能实现这个目标?

一如既往,感谢您的帮助。


您需要的比例是序数比例,如下所示:

var colourScale = d3.scale.ordinal()
    .domain(["Top Level","Second A", "Second B", "Second C", "Second D"])
    .range(["blue","red", "green", "purple", "gold"]);

然后,你就可以改变这一切......

.style("fill", function(d) {
    if (d.name == "Top Level") {
        return d._children ? "blue" : "#fff";
    }
    if (d.name == "Second A") {
        return d._children ? "red" : "#fff";
    }
    if (d.name == "Second B") {
        return d._children ? "green" : "#fff";
    }
    if (d.name == "Second C") {
        return d._children ? "purple" : "#fff";
    }
    if (d.name == "Second D") {
        return d._children ? "gold" : "#fff";
    }
})

...只是:

.style("fill", function(d) {
    return colourScale(d.name)
})

并且摆脱它linkColor功能。

请注意,尽管您已链接 D3 v5 文档,但您正在使用 D3 v3。

这是经过更改的代码:

var treeData = [{
  "name": "Top Level",
  "children": [{
    "name": "Second A",
    "children": [{
      "name": "Third A"
    }, {
      "name": "Third B"
    }]
  }, {
    "name": "Second B",
    "children": [{
      "name": "Third C"
    }, {
      "name": "Third D"
    }]
  }, {
    "name": "Second C",
    "children": [{
      "name": "Third E"
    }, {
      "name": "Third F"
    }]
  }, {
    "name": "Second D",
    "children": [{
      "name": "Third G"
    }, {
      "name": "Third H"
    }, ]
  }, ]
}];

var colourScale = d3.scale.ordinal()
  .domain(["Top Level", "Second A", "Second B", "Second C", "Second D"])
  .range(["blue", "red", "green", "purple", "gold"]);


// ************** Generate the tree diagram	 *****************
var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = 960 - margin.right - margin.left,
  height = 500 - margin.top - margin.bottom;

var i = 0,
  duration = 750,
  root;

var tree = d3.layout.tree()
  .size([height, width]);

var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.y, d.x];
  });

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;

update(root);

d3.select(self.frameElement).style("height", "500px");


// Collapse after the second level
root.children.forEach(collapse);

update(root);

// Collapse the node and all it's children
function collapse(d) {
  if (d.children) {
    d._children = d.children
    d._children.forEach(collapse)
    d.children = null
  }
}

function update(source) {



  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
    links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 180;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
      return "translate(" + source.y0 + "," + source.x0 + ")";
    })
    .on("click", click);

  nodeEnter.append("circle")
    .attr("r", 1e-6)
    .style("fill", function(d) {
      return d._children ? "#C0C0C0" : "#fff";
    });

  nodeEnter.append("text")
    .attr("x", function(d) {
      return d.children || d._children ? -13 : 13;
    })
    .attr("dy", ".35em")
    .attr("text-anchor", function(d) {
      return d.children || d._children ? "end" : "start";
    })
    .text(function(d) {
      return d.name;
    })
    .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + d.y + "," + d.x + ")";
    });

  nodeUpdate.select("circle")
    .attr("r", 10)
    .style("fill", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    })
    .style("stroke", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    });

  nodeUpdate.select("text")
    .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.y + "," + source.x + ")";
    })
    .remove();

  nodeExit.select("circle")
    .attr("r", 1e-6);

  nodeExit.select("text")
    .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll("path.link")
    .data(links, function(d) {
      return d.target.id;
    });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("stroke-width", function(d) {
      return 1;
    })
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .style("stroke", function(d) {
      return d.target.depth === 2 ? colourScale(d.target.parent.name) : colourScale(d.target.name);
    });

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", function(d) {
      var o = {
        x: source.x,
        y: source.y
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}


// Toggle children on click.
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(d);
}
.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
}

.link {
  fill: none;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何实现 D3 比例让孩子继承父母的颜色并带有刻度? 的相关文章

随机推荐

  • 文本词云绘制错误

    我有以下用于绘制词云的代码 并且收到后续错误 wordcloud dm word dm freq scale c 8 2 min freq 2 max words Inf random order FALSE rot per 15 colo
  • 在 Windows 上为 python 2.7 安装 gstreamer 1.0。

    我一直在尝试在 Windows 上安装 gstreamer 1 0 以用作 python 2 7 模块 我从这里安装了sdkhttp docs gstreamer com display GstSDK Installing on Windo
  • Tensorflow 错误“形状 Tensorshape() 必须具有等级 1”

    import tensorflow as tf import numpy as np import os from PIL import Image cur dir os getcwd def modify image image resi
  • 如何在 C# 中打印 PCL 文件?

    我有一个使用 打印到文件 生成的 PCL 文件 在 C 中以编程方式打印此文件的最佳方法是什么 当然 考虑到我要打印的打印机支持 PCL 我知道我可以通过从提示中调用来进行打印 copy filename pcl location prin
  • iOS App Store 提交:缺少图标 (Cordova)

    我正在制作 Cordova PhoneGap 应用程序并将其提交到 App Store 但是 我收到了一封电子邮件 其中包含以下消息 Invalid Icon Path No icon found at the path reference
  • SQL Server存储过程参数输出

    我有一个存储过程 为了这个问题的目的 我已经大大缩小了它的规模 但本质上我需要帮助的问题是这个 如果表中的一行xyz已更新 我需要将 ID 相互附加并输出回调用应用程序 更新按预期工作 问题在于我构建输出的方式 IPV ID Found 请
  • 在第三方 Django 应用程序中自定义模板

    我在 Django 项目中使用第三方应用程序 django social share 但我需要自定义模板 我不知道如何去做 我尝试的一切都继续使用默认模板 当前默认模板存储在 django social share django socia
  • 我在我的项目中添加 MPAndroidChart 但在我的 xml 中找不到 LineChart

    我想在我的项目中使用 MPAndroidChart 我在我的 gradle 中添加了该库 但在我的 xml 布局文件中 我找不到 Chart 我的 build gradle Module 是这样的 dependencies implemen
  • C# using 语句

    我真的很想把这件事从我的脑海里赶出去 请看下面的代码 using DataTable resultTable DBUtility GetSingleDBTableResult connectionString SELECT FROM MyD
  • SVG 图像未显示在 html 电子邮件中

    我已将 svg 图像嵌入到 html 电子邮件中 它显示在 iPhone 和桌面 Mac 邮件应用程序上 但未显示在我的 Mobileme Web 邮件上 有什么想法吗 这是代码 img src http ww
  • 使用第一类模块时,类型构造函数“...”将转义其范围

    给定一个简单的工厂 module type Factory sig type t val create unit gt t end module FactoryImpl Factory struct type t string let cr
  • 为什么 process.env.NODE_ENV 未定义?

    我正在尝试遵循有关 NodeJS 的教程 我不认为我错过了什么 但每当我打电话给process env NODE ENV我得到的唯一价值是undefined 根据我的研究 默认值应该是development 这个值是如何动态设置的以及它最初
  • 同时检查多个 URL 的页面加载时间

    如果 URL 作为输入给出 谁能指导我应该编写哪些 C 代码来获取每个 URL 的页面加载时间 OR 如果可能的话 请给我提供任何可以执行此操作的软件的链接 任何以多个 URL 作为输入并提供每个 URL 的页面加载时间的软件 您是否想要测
  • 模型执行后清除 Tensorflow GPU 内存

    我已经训练了 3 个模型 现在正在运行代码 按顺序加载 3 个检查点并使用它们运行预测 我正在使用 GPU 当第一个模型加载时 它会预先分配整个 GPU 内存 我希望用它来处理第一批数据 但完成后它不会卸载内存 当加载第二个模型时 使用两者
  • C# REST webservice身份验证问题

    在我之前的问题中here https stackoverflow com questions 3812625 c problem authenticating webservice between two webapplications我在
  • 如何在 VBA (Excel) 中使用变量设置属性

    采取这个代码 With ActiveSheet Shapes AddShape msoShapeRectangle x y w h TextFrame Parent Line Visible False Parent Fill ForeCo
  • 通用类型的 ASP.NET MVC 显示模板

    我正在尝试使用模型 ListModel 作为通用列表模型 我想在页面输入 Html DisplayForModel 但是 MVC 无法正确找到模板文件 ListModel cshtml 对于通用模型来说 它的工作方式必须有所不同 我应该如何
  • C linux相当于windows QueryPerformanceCounter

    Linux 中是否有等效的 C 函数用于读取 CPU 计数器及其频率 我正在寻找类似于 QueryPerformanceCounter 函数的东西 该函数读取现代 CPU 中的 64 位计数器 clock gettime 2 http li
  • HttpURLConnection conn.getRequestProperty 返回 null

    我正在尝试将一些数据推送到 BED 的 URL MDS CS 当我在代码中设置一些请求标头并提交请求时 提交的请求标头设置为null 这是我的代码 HttpURLConnection conn HttpURLConnection url o
  • 如何实现 D3 比例让孩子继承父母的颜色并带有刻度?

    我有一个 D3 js 树 它对节点和链接应用了不同的颜色 颜色是硬编码的 nodeUpdate select circle attr r 10 style fill function d if d name Top Level return