d3.js 为 Y 轴包装长标签

row*_*oat 5 javascript d3.js

参考Mike Bostock 的这个示例,我想将相同的想法应用于 X 和 Y 切换的条形图。所以标签沿着 Y 轴上下运行。

在这个小提琴中:http : //jsfiddle.net/2eLW6/我只是从 Mike 的示例中复制 wrap 函数并将其应用于我的图表。

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);
      }
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

在 Mike 将其应用于 x 轴的示例中,只有在超过特定行长时才会将单词放在新行上。在我的小提琴中,它将每个单词都放在一个新行上。另外,我想知道是否有办法将 y 属性向上移动一点,如果创建了一条新线使其仍然居中?

谁能帮我翻译 wrap() 函数的 y 轴?

wrap() 函数在第 203 行定义,并从该小提琴中的第 135 行调用。

emi*_*ara 1

我正在寻找这个问题的解决方案,并发现 Mike Bostock 发布了一个工作示例。该示例适用于 x 轴,但可以轻松地适用于 y 轴。该wrap()函数不需要修改,而是必须将其应用于 y 轴,指示可能适用的正确宽度变量。

在原始示例中,垂直图表的wrap()调用方式如下:

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

水平图表的具体细节可能会有所不同,但保存宽度值的典型变量是 margin.left,如以下代码片段所示:

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
.selectAll(".tick text")
  .call(wrap, margin.left);
Run Code Online (Sandbox Code Playgroud)

OP 中要求的其余功能将需要修改wrap()