Right to Left tree direction in D3

Viewed 406

How can I set D3 tree direction to right to left?

I'm using following code in order to render the tree, but I would like to set the direction to right to left:

This is a treemap implemented by D3 and its current direction is LTR and also it is a collapsible tree.

var treeData = "";

var margin = { top: 20, right: 90, bottom: 30, left: 90 },
    width = 1900 - margin.left - margin.right,
    height = 900 - margin.top - margin.bottom;

var svg = d3.select("#chart").append("svg")       
    .attr("width", 1600)
    .attr("height", 3200)
    .append("g")
    .attr("transform", "translate("
    + margin.left + "," + margin.top + ")");

var i = 0,
    duration = 2000,
    root;

var treemap = d3.tree().size([height, width]);

root = d3.hierarchy(treeData, function (d) { return d.children; });
root.x0 = height / 2;
root.y0 = 0;

root.children.forEach(collapse);

update(root);

function collapse(d) {

}

function update(source) {
}
1 Answers

There is an example that shows how to do that, but it is based on D3.js v.3.

You can also play with d3.linkHorizontal().x(d => width - d.y). For the left-to-right trees it's d3.linkHorizontal().x(d => d.y) - please, don't ask me why the .x(...) returns d.y.

A simpler approach is just to flip the <svg> with transform, and then flip all the <text> elements back and align them a little:

  svg.attr("transform", "scale(-1, 1)");
  svg
    .selectAll("text")
    .attr("transform", "scale(-1, 1)")
    .attr("text-anchor", (d) => (d.depth === 0 ? "start" : "end"))
    .attr("x", function (d) {
      return d3.select(this).attr("text-anchor") === "start" ? 6 : -6;
    });

Here is a working example: https://observablehq.com/@romaklimenko/right-to-left-tidy-tree

Related