在d3 v4网络图中为节点添加不同的图像

时间:2017-08-29 14:45:04

标签: image d3.js

我知道有一些主题可以讨论这个问题但是找不到的结果对我有用。我正在尝试修改经典的d3网络图悲惨的例子(d3v4版本HERE:https://bl.ocks.org/mbostock/4062045)为不同的节点添加不同的图像 - 文件的相对路径作为节点属性之一给出,例如。

 {"id": "Valjean", "group": 1, img: "images/male.png"},

我想要实现的目标与此类似:https://bl.ocks.org/mbostock/950642但在d3v4中制作,不同节点的图像不同。

我找到的所有示例(也是this承诺代码片段,遗憾的是对我不起作用)指向类似的方法,它看起来或多或少像这样(在d3 v4和v3中):

node.append("image")
      .attr("xlink:href", function(d) { return d.img })
      .attr("x", -8)
      .attr("y", -8)
      .attr("width", 16)
      .attr("height", 16);

然而,尽管花了几个小时,但我无法使其发挥作用。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

以下是一个快速示例,它将您的data示例与基于v4示例的图片相结合:

v3

添加图片应该就像更改<!DOCTYPE html> <meta charset="utf-8"> <style> .links line { stroke: #999; stroke-opacity: 0.6; } .nodes circle { stroke: #fff; stroke-width: 1.5px; } </style> <svg width="960" height="600"></svg> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); var color = d3.scaleOrdinal(d3.schemeCategory20); var simulation = d3.forceSimulation() .force("link", d3.forceLink().id(function(d) { return d.id; })) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width / 2, height / 2)); d3.json("https://jsonblob.com/api/9f7e2c48-8ccd-11e7-8b46-ef38640909a4", function(error, graph) { if (error) throw error; var link = svg.append("g") .attr("class", "links") .selectAll("line") .data(graph.links) .enter().append("line") .attr("stroke-width", function(d) { return Math.sqrt(d.value); }); var node = svg.append("g") .attr("class", "nodes") .selectAll("image") .data(graph.nodes) .enter().append("image") .attr("xlink:href", "https://github.com/favicon.ico") .attr("x", -8) .attr("y", -8) .attr("width", 16) .attr("height", 16) .call(d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); node.append("title") .text(function(d) { return d.id; }); simulation .nodes(graph.nodes) .on("tick", ticked); simulation.force("link") .links(graph.links); function ticked() { link .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); } }); function dragstarted(d) { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; } function dragged(d) { d.fx = d3.event.x; d.fy = d3.event.y; } function dragended(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; } </script> d.fx = d3.event.x; d.fy = d3.event.y; } function dragended(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; } </script>到:

一样简单
.attr("xlink:href"