d3.js将sankey拖放到v4的拖放功能

时间:2018-01-24 19:47:46

标签: d3.js

任何人都设法制作了这个例子

Sankey diagram with horizontal and vertical node movement

在v4中工作

因为sankey.relayout()不再可用 d3.drag已经没有.origin了。

尝试拖动节点时我尝试做了最疯狂的事情,并且由于某些行为在sankey和drag规范中都发生了变化,我无法想象如何将示例迁移到v4。

var graph = { "nodes": [...], "links": [...] }; 
var layout = d3.sankey();

layout
    .extent([[1, 1], [width - 1, height - 6]])
    .nodeId(function (d) {
        return d.id;
    })
    .nodeWidth(12)
    .nodePadding(padding)
    .nodeAlign(d3.sankeyRight)

layout(graph);

// Add Links
var link = svg.append("g")
    .attr("fill", "none")
    .selectAll(".link")
      .data(graph.links)
      .enter()
      .append("g")
      .attr("class", "link")

link.append("path")
.attr("d", d3.sankeyLinkHorizontal())
.attr("stroke", "#000")
.style("stroke-width", function (d) {
    return d.width;
})
    .append("title")
    .text("Some text");


// Drag behavior for node elements
var drag = d3.drag()
   //.origin(function (d) { return d; }) // Deprecated but maybe unnecessary
   .on("drag", dragmove)

// Add nodes
var node = svg.append("g")
        .selectAll(".node")
          .data(graph.nodes)
          .enter()
            .append("g")  
            .attr("transform", function (d) {
                return "translate(" + [d.x0, d.y0] + ")";
            })
            .call(drag)  // The g element should be now draggable

// Add element inside g element
node.append("rect")
    .attr("height", function (d) { return d.y1 - d.y0; })
    .attr("width", function (d) { return d.x1 - d.x0; })
    .attr("fill", ...)

node.append("text")
    .attr("x", function (d) { return (d.x1 - d.x0) - 6; })
    .attr("y", function (d) { return (d.y1 - d.y0) / 2; })
    .attr("dy", "0.35em")
    .attr("text-anchor", "end")
    .text(function (d) { return d.name; })
    .filter(function (d) { return d.x0 < width / 2; })
    .attr("x", function (d) { return (d.x1 - d.x0) + 6 })
    .attr("text-anchor", "start");


// Called by d3.drag
function dragmove(d) { 

        var dx = Math.round(d.x = Math.max(0, Math.min(width , evt.x)));
        var dy = Math.round(d.y = Math.max(0, Math.min(height, evt.y)));

        d3.select(this).attr("transform", "translate(" + [dx, dy] + ")")

        // Now should redraw the links but 
        sankey.relayout(); // not a function anymore.


        // path references sankey.link() that is also deprecated in v4 in 
        // favour of d3.sankeyLinkHorizontal() ? (I'm not sure)
        // link references the g element containing the path elements 
        // classed .link
        link.attr("d", path);

};

0 个答案:

没有答案