Javascript 当文字变长时,我的D3Y轴溢出,如何在图表中打断文字?

Javascript 当文字变长时,我的D3Y轴溢出,如何在图表中打断文字?,javascript,d3.js,Javascript,D3.js,如何为y轴上生成的每个文本添加打断。我完全无法更新js中的文本您可以使用wrap函数在axis标签中包装长文本 svg.append("g").attr("class", "y axis").transition().call(yAxis); 像这样打电话 function wrap(text, width) { text.each(function() { var text = d3.select(this), words = text.text().split(

如何为y轴上生成的每个文本添加打断。我完全无法更新js中的文本

您可以使用wrap函数在axis标签中包装长文本

svg.append("g").attr("class", "y axis").transition().call(yAxis);
像这样打电话

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"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    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);
      }
    }
  });
}
这是针对x轴的,如果需要y轴,则需要将其应用于y轴

svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .selectAll(".tick text")
      .call(wrap, x.rangeBand());