D3 - Responsive axis labels

Asked by At

I have a demo here

I have a responsive D3 chart that becomes narrower when the window is resized.

My problem is the x axis labels they could be long and I need them to become narrower when the window is resized.

I'm trying to use the example from Mick Bostock but my example needs to respond when the window is resized.

private insertLinebreak(this:SVGTextElement, text) {
    text.each(function() {
      const text = d3.select(this);
      const words = text.text().split(/\s+/).reverse();
      let word = "";
      let line = [];
      let lineNumber = 0;
      const lineHeight = 1.1;
      const y = text.attr("y");
      const dy = parseFloat(text.attr("dy"));
      let tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
      const width = this.x.rangeBand()
      while (word = words.pop()) {
        line.push(word);
        tspan.text(line.join(" "));
        if (tspan.node().getComputedTextLength() > width) {
          line.pop();
          tspan.text(line.join(" "));
          line = [word];
          tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
        }
      }
    });

Any help on how I might get this to work

0 Answers