【问题标题】:How to convert to D3's JSON format?如何转换为 D3 的 JSON 格式?
【发布时间】:2012-06-20 17:52:33
【问题描述】:

虽然遵循众多 D3 示例,但数据通常以flare.json 中给出的格式格式化:

{
 "name": "flare",
 "children": [
  {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "AgglomerativeCluster", "size": 3938},
      :

我有一个邻接列表如下:

A1 A2
A2 A3
A2 A4

我想将其转换为上述格式。目前,我正在服务器端执行此操作,但有没有办法使用 d3 的功能来实现这一点?我找到了一个here,但该方法似乎需要修改 d3 核心库,由于可维护性,我不赞成这样做。有什么建议吗?

【问题讨论】:

  • “邻接表”是什么意思?
  • 我认为他的意思是[(A1, A2), (A2, A3), (A2, A4)]
  • @sczizzo:是的,我就是这个意思!对不起,宝贝。我应该更清楚。

标签: javascript json graph d3.js tree


【解决方案1】:

没有规定的格式,因为您通常可以通过各种访问器函数(例如hierarchy.children)和array.map 重新定义数据。但是您引用的格式可能是树最方便的表示,因为它适用于默认访问器。

第一个问题是您打算显示graph 还是tree。对于图,数据结构是根据nodeslinks 定义的。对于树,布局的输入是根节点,它可能有一个child nodes 的数组,其叶节点有一个关联的value

如果你想显示一个图形,而你只有一个边列表,那么你需要遍历边以生成一个节点数组和一个链接。假设您有一个名为“graph.csv”的文件:

source,target
A1,A2
A2,A3
A2,A4

您可以使用d3.csv 加载此文件,然后生成一个节点和链接数组:

d3.csv("graph.csv", function(links) {
  var nodesByName = {};

  // Create nodes for each unique source and target.
  links.forEach(function(link) {
    link.source = nodeByName(link.source);
    link.target = nodeByName(link.target);
  });

  // Extract the array of nodes from the map by name.
  var nodes = d3.values(nodeByName);

  function nodeByName(name) {
    return nodesByName[name] || (nodesByName[name] = {name: name});
  }
});

然后您可以将这些节点和链接传递给力布局以可视化图表:

如果您想生成一个,那么您需要进行稍微不同的数据转换形式来为每个父节点累积子节点。

d3.csv("graph.csv", function(links) {
  var nodesByName = {};

  // Create nodes for each unique source and target.
  links.forEach(function(link) {
    var parent = link.source = nodeByName(link.source),
        child = link.target = nodeByName(link.target);
    if (parent.children) parent.children.push(child);
    else parent.children = [child];
  });

  // Extract the root node.
  var root = links[0].source;

  function nodeByName(name) {
    return nodesByName[name] || (nodesByName[name] = {name: name});
  }
});

像这样:

【讨论】:

  • +1 非常感谢您的时间和详细的解释。它消除了我的一些误解。
  • 考虑使用 d3 的嵌套功能作为此方法的一部分,将您的 csv 转换为不同的树结构github.com/mbostock/d3/wiki/Arrays#-nest
  • @mbostock,感谢您的回答,您是否对您的代码进行了改编以绘制此类图形bl.ocks.org/mbostock/1062288?非常感谢
【解决方案2】:

D3 不需要特定格式。这完全取决于您的应用程序。您当然可以将邻接列表转换为flare.json 中使用的格式,但这又将是特定于应用程序的代码。通常,您不能这样做,因为邻接列表没有构建树所需的“头”或“根”元素。此外,您还需要单独处理循环、孤儿等。

鉴于您目前正在服务器端进行转换,我很想说“如果它没有损坏,请不要修复它”;)

【讨论】:

    猜你喜欢
    • 2020-08-30
    • 1970-01-01
    • 2019-11-12
    • 2016-06-12
    • 2021-10-06
    • 1970-01-01
    • 2019-08-09
    • 2014-10-26
    • 1970-01-01
    相关资源
    最近更新 更多