ONSvisual / Simple-charts

Simple responsive charts
16 stars 12 forks source link

Can we add bostock's wrap function to horizontal charts #12

Closed henryjameslau closed 5 years ago

henryjameslau commented 5 years ago

So the labels will wrap if they are long

henryjameslau commented 5 years ago
  function wrap(text, width) {
        text.each(function() {
          var text = d3.select(this),
              words = text.text().split(/\s+/).reverse(),
              word,
              line = [],
              lineNumber = 0,
              lineHeight = 1.1, // ems
              y = text.attr("y"),
              x = text.attr("x"),
              dy = parseFloat(text.attr("dy")),
              tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
          while (word = words.pop()) {
            line.push(word);
            tspan.text(line.join(" "));
            if (tspan.node().getComputedTextLength() > width) {
              tspan.attr("dy",(dy-0.55)+"em")
              line.pop();
              tspan.text(line.join(" "));
              line = [word];
              tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy -0.55 + "em").text(word);
            }
          }
        });
      }

This one only works for two lines of tspans

henryjameslau commented 5 years ago

One that works for three lines

    function wrap(text, width) {
      text.each(function() {
        var text = d3.select(this),
            words = text.text().split(/\s+/).reverse(),
            word,
            line = [],
            lineNumber = 0,
            lineHeight = 1.1, // ems
            y = text.attr("y"),
            x = text.attr("x"),
            dy = parseFloat(text.attr("dy")),
            tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
        while (word = words.pop()) {
          line.push(word);
          tspan.text(line.join(" "));
          if (tspan.node().getComputedTextLength() > width) {
            if(lineNumber==0){tspan.attr("dy",-1.1+"em")}else{tspan.attr("dy",+1.1+"em")}
            line.pop();
            tspan.text(line.join(" "));
            line = [word];
            ++lineNumber;
            tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", 1.1 + "em").text(word);
          }
        }
      });
    }
JureStabuc commented 5 years ago

Done - horizontal simple and stacked bar.