首页 > 解决方案 > 使用 d3.js 树形图块进行文本响应

问题描述

我正在使用 d3.js 树图布局。在图块中,字体大小太小。如何在大图块中以较大字体显示,对于小图块以较小字体显示,或在每个图块的中心显示标签文本。在这里找到我的代码链接https://codesandbox.io/s/loving-mccarthy-wfbtg。标签可以居中,并且可以增加字体大小以获得更好的视图。标题还包含我不想显示如何单独删除面包屑标题中的计数的总数。 图片

逻辑在这里

createTreeChart = () => {
    const width = 550;
    const height = 600;
    const padding = 60;
    const format = d3.format(",d");
    const name = d =>
      d
        .ancestors()
        .reverse()
        .map(d => d.data.name)
        .join("/");
    function tile(node, x0, y0, x1, y1) {
      d3.treemapBinary(node, 0, 0, width, height);
      for (const child of node.children) {
        child.x0 = x0 + (child.x0 / width) * (x1 - x0);
        child.x1 = x0 + (child.x1 / width) * (x1 - x0);
        child.y0 = y0 + (child.y0 / height) * (y1 - y0);
        child.y1 = y0 + (child.y1 / height) * (y1 - y0);
      }
    }
    const treemap = data =>
      d3.treemap().tile(tile)(
        d3
          .hierarchy(data)
          .sum(d => d.value)
          .sort((a, b) => b.value - a.value)
      );
    const svg = d3
      .select("#chart")
      .append("svg")
      .attr("viewBox", [0.5, -30.5, width, height + 30])
      .style("font", "10px sans-serif");

    const x = d3.scaleLinear().rangeRound([0, width]);
    const y = d3.scaleLinear().rangeRound([0, height]);

    // const svg = d3
    //   .create("svg")
    //   .select("#chart")
    //   .append("svg")
    //   .attr("viewBox", [0.5, -30.5, width, height + 30])
    //   .style("font", "10px sans-serif");

    let group = svg.append("g").call(render, treemap(data));

    function render(group, root) {
      const node = group
        .selectAll("g")
        .data(root.children.concat(root))
        .join("g");

      node
        .filter(d => (d === root ? d.parent : d.children))
        .attr("cursor", "pointer")
        .on("click", d => (d === root ? zoomout(root) : zoomin(d)));

      node.append("title").text(d => `${name(d)}\n${format(d.value)}`);

      node
        .append("rect")
        .attr("id", d => (d.leafUid = "leaf"))
        .attr("fill", d => (d === root ? "#fff" : d.children ? "#ccc" : "#ddd"))
        .attr("stroke", "#fff");

      node
        .append("clipPath")
        .attr("id", d => (d.clipUid = "clip"))
        .append("use")
        .attr("xlink:href", d => d.leafUid.href);

      node
        .append("text")
        .attr("clip-path", d => d.clipUid)
        .attr("font-weight", d => (d === root ? "bold" : null))
        .selectAll("tspan")
        .data(d =>
          (d === root ? name(d) : d.data.name)
            .split(/(?=[A-Z][^A-Z])/g)
            .concat(format(d.value))
        )
        .join("tspan")
        .attr("x", 3)
        .attr(
          "y",
          (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + 1.1 + i * 0.9}em`
        )
        .attr("fill-opacity", (d, i, nodes) =>
          i === nodes.length - 1 ? 0.7 : null
        )
        .attr("font-weight", (d, i, nodes) =>
          i === nodes.length - 1 ? "normal" : null
        )
        .text(d => d);

      group.call(position, root);
    }

    function position(group, root) {
      group
        .selectAll("g")
        .attr("transform", d =>
          d === root ? `translate(0,-30)` : `translate(${x(d.x0)},${y(d.y0)})`
        )
        .select("rect")
        .attr("width", d => (d === root ? width : x(d.x1) - x(d.x0)))
        .attr("height", d => (d === root ? 30 : y(d.y1) - y(d.y0)));
    }

    // When zooming in, draw the new nodes on top, and fade them in.
    function zoomin(d) {
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.append("g").call(render, d));

      x.domain([d.x0, d.x1]);
      y.domain([d.y0, d.y1]);

      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .call(position, d.parent)
        )
        .call(t =>
          group1
            .transition(t)
            .attrTween("opacity", () => d3.interpolate(0, 1))
            .call(position, d)
        );
    }

    // When zooming out, draw the old nodes on top, and fade them out.
    function zoomout(d) {
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.insert("g", "*").call(render, d.parent));

      x.domain([d.parent.x0, d.parent.x1]);
      y.domain([d.parent.y0, d.parent.y1]);

      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .attrTween("opacity", () => d3.interpolate(1, 0))
            .call(position, d)
        )
        .call(t => group1.transition(t).call(position, d.parent));
    }

    return svg.node();
  };

标签: javascriptreactjsd3.js

解决方案


更改font-size文本节点的属性。添加.attr("font-size", ...)如下。

node
    .append("text")
    .attr("clip-path", d => d.clipUid)
    .attr("font-weight", d => (d === root ? "bold" : null))
    .attr("font-size", d => {
          if (d === root) return "1em";
          const width = x(d.x1) - x(d.x0), height = y(d.y1) - y(d.y0);
          return Math.max(Math.min(width/5, height/2, Math.sqrt((width*width + height*height))/10), 9)
        })
    .selectAll("tspan")
    ...

font-size会将每个矩形的对角线设置为 10%。如果文本变得太小而无法阅读,font-size则设置为最小值 9。对于垂直长的矩形,文本可能会变得太大,因此最大值设置为矩形宽度的五分之一或高度的一半矩形,以较大者为准。

缩放后字体大小无法正确缩放,因为x缩放y的域仅在render. render在调用zoominzoomout函数之前更新域。

function zoomin(d) {
      x.domain([d.x0, d.x1]);
      y.domain([d.y0, d.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.append("g").call(render, d));
      ...
    }

function zoomout(d) {
      x.domain([d.parent.x0, d.parent.x1]);
      y.domain([d.parent.y0, d.parent.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.insert("g", "*").call(render, d.parent));
      ...
    }

面包屑修复。当您设置矩形的tspans'xy时,您也在使用相同的逻辑设置面包屑中的sx和。解决这个问题的最简单方法是简单地制作面包屑。然而,这限制了面包屑的样式。相反,在渲染函数的末尾单独设置面包屑文本的样式。ytspantspan

...
        .text(d => d);

      node.selectAll('text').filter(d => d === root)
        .selectAll("tspan").attr("y", '1.1em').attr("x", undefined);

      group.call(position, root);

面包屑文本的正则表达式看起来并不奏效。它在奇怪的地方分隔文本。更改name(d).split(/(?=[A-Z][^A-Z])/g)name(d).split(/(?=\/)/g)

文字居中。有很多事情要做。文本锚点设置为中间,transform: translate文本框设置为宽度/高度的一半。

        .attr("text-anchor", d => d === root ? null : "middle")
        .attr("transform", d=> d === root ? null : 
          `translate(${(x(d.x1) - x(d.x0))/2}, ${(y(d.y1) - y(d.y0))/2})`)
        .selectAll("tspan")

并更改tspans'y使它们垂直居中。

        .attr("x", 3)
        .attr(
          "y",
          (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + (i - nodes.length/2) * 0.9}em`
        )

推荐阅读