D3中的非分层(组间没有间隙)捆绑布局

时间:2015-02-07 21:37:58

标签: javascript svg d3.js bundle-layout

我正在尝试使用D3进行捆绑布局。但是,我想使它成为非分层(或伪非分层),以便在边缘节点之间没有间隙。希望下面的图像可以作为我想要删除的间隙的一个很好的例子(见不同颜色文本之间的图像顶部)。

Bundle chart

我试图通过以下两种方式来解决这个问题:通过用泛型类型替换区分节点类型的类型,并用作者的名称替换节点类型(从而使所有节点成为不同的类型,强制等间距) 。这些尝试的前者类似于针对this查询而提出的建议。

然而,当我运行

行时
 var nodes = cluster.nodes(packageHierarchy(theArr, id_to_user_dict)); 

我不可避免地得到错误“Uncaught TypeError:无法读取未定义的属性'parent'。”如何在这些数据上强制使用通用根,以便我的代码正常工作?

我为生成包含图表的代码结构的代码如下所示。我在上面提出的两个解决方案在“包层次结构”功能中被注释掉了。请注意,它源自Bostock's sample for hierarchical edge bundling

function packageHierarchy(classes, dictionary) {
for (var i = 0; i < classes.length; i++){
    var imports = [];
    // classes[i].name = "root" + "^" + classes[i]["author"];
    // classes[i].name = classes[i]["author"] + "^" + classes[i]["author"];
    classes[i].name = classes[i]["type"] + "^" + classes[i]["author"];
    for (var j = 0; j < classes[i]["values"].length; j++){
        if (classes[i]["values"][j]["type"] == "comments"){
            var responseObj = classes[i]["values"][j]["in_response_to"];
            var responseAuthor = dictionary[classes[i]["values"][j]["in_response_to"]];
            if (responseAuthor != undefined){
                imports.push(responseAuthor);
            }
        }
    }
    classes[i].imports = imports;

}


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.indexOf("^")));
                node.parent.children.push(node);
                node.key = name.substring(i + 1);
        }
    }
    return node;
}

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

return map[""];
}

1 个答案:

答案 0 :(得分:1)

你已经提到了解决方案的两个想法,但是,我会建议第三种,完全不同的想法。

组之间的距离由D3簇布局决定。默认行为是在组之间留出一个节点大小的空白空间。

我有这个涉及D3捆绑布局的代码片段,组之间有默认的差距:

var diameter = 300,
    radius = diameter / 2,
    innerRadius = radius - 80;

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 classes = getData();

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

svg.selectAll(".link")
    .data(bundle(links))
   .enter()
    .append("path")
    .attr("class", "link")
    .attr("d", line);

svg.selectAll(".node")
    .data(nodes.filter(function(n) { return !n.children; }))
   .enter()
    .append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
        return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
    })
    .append("text")
    .attr("dx", function(d) { return d.x < 180 ? 8 : -8; })
    .attr("dy", ".31em")
    .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
    .attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; })
    .text(function(d) { return d.key; });

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;
}

function getData() {
    return [
        {"name":"Female.Ann",     "imports":["Male.Andrew"]},
        {"name":"Female.Brenda",  "imports":["Male.Bill"]},
        {"name":"Female.Claudia", "imports":["Male.Andrew"]},
        {"name":"Female.Claudia", "imports":["Male.Bill"]},
        {"name":"Female.Deborah", "imports":["Male.Darryl"]},
        {"name":"Female.Emily",   "imports":["Male.Andrew"]},
        {"name":"Female.Flora",   "imports":["Male.Darryl"]},
        {"name":"Female.Gia",     "imports":["Male.Darryl"]},
        {"name":"Female.Hannah",  "imports":["Male.Curtis"]},
        {"name":"Female.Irene",   "imports":["Male.Hugh"]},
        {"name":"Male.Andrew",    "imports":["Female.Emily"]},
        {"name":"Male.Bill",      "imports":["Female.Emily"]},
        {"name":"Male.Curtis",    "imports":["Female.Emily"]},
        {"name":"Male.Darryl",    "imports":["Female.Claudia"]},
        {"name":"Male.Edgar",     "imports":["Female.Claudia"]},
        {"name":"Male.Franklin",  "imports":["Female.Claudia"]},
        {"name":"Male.George",    "imports":["Female.Claudia"]},
        {"name":"Male.Hugh",      "imports":["Female.Claudia"]},
    ];
};
.node {
  font: 11px "Helvetica Neue", Helvetica, Arial, sans-serif;
}

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

enter image description here

可以通过向群集布局提供自定义separation()功能来修改此问题。

在以下代码段中,我只添加了一行:

    .separation(function(a, b) { return 1; })

并且差距消失了!

var diameter = 300,
    radius = diameter / 2,
    innerRadius = radius - 80;

var cluster = d3.layout.cluster()
    .separation(function(a, b) { return 1; })
    .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 classes = getData();

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

svg.selectAll(".link")
    .data(bundle(links))
   .enter()
    .append("path")
    .attr("class", "link")
    .attr("d", line);

svg.selectAll(".node")
    .data(nodes.filter(function(n) { return !n.children; }))
   .enter()
    .append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
        return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
    })
    .append("text")
    .attr("dx", function(d) { return d.x < 180 ? 8 : -8; })
    .attr("dy", ".31em")
    .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
    .attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; })
    .text(function(d) { return d.key; });

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;
}

function getData() {
    return [
        {"name":"Female.Ann",     "imports":["Male.Andrew"]},
        {"name":"Female.Brenda",  "imports":["Male.Bill"]},
        {"name":"Female.Claudia", "imports":["Male.Andrew"]},
        {"name":"Female.Claudia", "imports":["Male.Bill"]},
        {"name":"Female.Deborah", "imports":["Male.Darryl"]},
        {"name":"Female.Emily",   "imports":["Male.Andrew"]},
        {"name":"Female.Flora",   "imports":["Male.Darryl"]},
        {"name":"Female.Gia",     "imports":["Male.Darryl"]},
        {"name":"Female.Hannah",  "imports":["Male.Curtis"]},
        {"name":"Female.Irene",   "imports":["Male.Hugh"]},
        {"name":"Male.Andrew",    "imports":["Female.Emily"]},
        {"name":"Male.Bill",      "imports":["Female.Emily"]},
        {"name":"Male.Curtis",    "imports":["Female.Emily"]},
        {"name":"Male.Darryl",    "imports":["Female.Claudia"]},
        {"name":"Male.Edgar",     "imports":["Female.Claudia"]},
        {"name":"Male.Franklin",  "imports":["Female.Claudia"]},
        {"name":"Male.George",    "imports":["Female.Claudia"]},
        {"name":"Male.Hugh",      "imports":["Female.Claudia"]},
    ];
};
.node {
  font: 11px "Helvetica Neue", Helvetica, Arial, sans-serif;
}

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