javascript - d3.js 分层边缘捆绑 : embed json data in variable

标签 javascript json d3.js

例如,我想直接读取变量中的 json 数据

var HEBdata = [
{"name":"test.cluster1.item1","imports":["test.cluster1.item2","test.cluster1.item3"]},
{"name":"test.cluster1.item2","imports":["test.cluster1.item3"]},
{"name":"test.cluster1.item3"}
];

然后我会在这里使用这个变量

d3.json(HEBdata, function(error, classes) {
  if (error) throw error;

而不是

d3.json("https://gist.githubusercontent.com/mbostock/1044242/raw/8f22cf2264e1f6ec6cb233c4b49333fb8f75bb99/readme-flare-imports.json", function(error, classes) {
  if (error) throw error;

这是一个您可以更改的代码:https://fiddle.jshell.net/d1766z4r/ (URL 已被注释并替换为 HEBdata 变量)

我希望这样做是为了能够使用自定义数据来简化我稍后想问的另一个问题。

最佳答案

不要使用 d3.json。相反,只需将对象分配给您的 var classes

d3.json 本质上是这样做的:

loads data into the browser using an XMLHttpRequest, or XHR. This allows data to be loaded asynchronously (so the rest of the page can display while data is loading), and is safer than JSONP. D3’s xhr module simplifies loading and parsing data. When loading data asynchronously, code that depends on the loaded data should generally exist within the callback function. Code that doesn't depend on data can run immediately when the page loads.

https://github.com/d3/d3-3.x-api-reference/blob/master/Requests.md

由于您已经准备好数据,因此无需等待即可使用。因此,任何通常必须等待收到 Http 响应才能运行的代码都可以立即运行,如下所示:

var classes = [
{"name":"test.cluster1.item1","imports":["test.cluster1.item2","test.cluster1.item3"]},
{"name":"test.cluster1.item2","imports":["test.cluster1.item3"]},
{"name":"test.cluster1.item3"}
];

var diameter = 960,
    radius = diameter / 2,
    innerRadius = radius - 120;

var cluster = d3.layout.cluster()
    .size([360, innerRadius])
    .sort(null)
    .value(function(d) { return d.size; });

var bundle = d3.layout.bundle();

var line = d3.svg.line.radial()
    .interpolate("bundle")
    .tension(.85)
    .radius(function(d) { return d.y; })
    .angle(function(d) { return d.x / 180 * Math.PI; });

var svg = d3.select("body").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
  .append("g")
    .attr("transform", "translate(" + radius + "," + radius + ")");

var link = svg.append("g").selectAll(".link"),
    node = svg.append("g").selectAll(".node");

//d3.json("https://gist.githubusercontent.com/mbostock/1044242/raw/8f22cf2264e1f6ec6cb233c4b49333fb8f75bb99/readme-flare-imports.json", function(error, classes) {
  //if (error) throw error;

  var nodes = cluster.nodes(packageHierarchy(classes)),
      links = packageImports(nodes);

  link = link
      .data(bundle(links))
    .enter().append("path")
      .each(function(d) { d.source = d[0], d.target = d[d.length - 1]; })
      .attr("class", "link")
      .attr("d", line);

  node = node
      .data(nodes.filter(function(n) { return !n.children; }))
    .enter().append("text")
      .attr("class", "node")
      .attr("dy", ".31em")
      .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + (d.y + 8) + ",0)" + (d.x < 180 ? "" : "rotate(180)"); })
      .style("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
      .text(function(d) { return d.key; })
      .on("mouseover", mouseovered)
      .on("mouseout", mouseouted);
//});

function mouseovered(d) {
  node
      .each(function(n) { n.target = n.source = false; });

  link
      .classed("link--target", function(l) { if (l.target === d) return l.source.source = true; })
      .classed("link--source", function(l) { if (l.source === d) return l.target.target = true; })
    .filter(function(l) { return l.target === d || l.source === d; })
      .each(function() { this.parentNode.appendChild(this); });

  node
      .classed("node--target", function(n) { return n.target; })
      .classed("node--source", function(n) { return n.source; });
}

function mouseouted(d) {
  link
      .classed("link--target", false)
      .classed("link--source", false);

  node
      .classed("node--target", false)
      .classed("node--source", false);
}

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

// Lazily construct the package hierarchy from class names.
function packageHierarchy(classes) {
  var map = {};

  function find(name, data) {
    var node = map[name], i;
    if (!node) {
      node = map[name] = data || {name: name, children: []};
      if (name.length) {
        node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
        node.parent.children.push(node);
        node.key = name.substring(i + 1);
      }
    }
    return node;
  }

  classes.forEach(function(d) {
    find(d.name, d);
  });

  return map[""];
}

// Return a list of imports for the given array of nodes.
function packageImports(nodes) {
  var map = {},
      imports = [];

  // Compute a map from name to node.
  nodes.forEach(function(d) {
    map[d.name] = d;
  });

  // For each import, construct a link from the source to target node.
  nodes.forEach(function(d) {
    if (d.imports) d.imports.forEach(function(i) {
      imports.push({source: map[d.name], target: map[i]});
    });
  });

  return imports;
}
.node {
  font: 300 11px "Helvetica Neue", Helvetica, Arial, sans-serif;
  fill: #bbb;
}

.node:hover {
  fill: #000;
}

.link {
  stroke: steelblue;
  stroke-opacity: .4;
  fill: none;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

fiddle :https://fiddle.jshell.net/ga1s8bn7/

关于javascript - d3.js 分层边缘捆绑 : embed json data in variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39147709/

相关文章:

javascript - 如何在 webpack.config.js 中使用 .babelrc 插件选项

javascript - 未找到 uws - 使用 SocketIO 的 VueJS

javascript - 如何访问 JSON 对象中的值?

javascript - D3 v4 - 获取当前缩放比例?

javascript - for循环字符串每个单词

javascript - 自定义滚动动画 - 暂停部分和水平滚动元素

json - R、GeoJSON 和传单

php - PHP 中两个 mysql 表的 Json 需要按层次结构输出

javascript - 从 lift snippet 中获取 d3 中的 json 数据

javascript - 我无法获得以下代码的输出