如何在D3折线图上拟合可变长度刻度标签?

vre*_*sys 12 javascript svg d3.js

这是一个JSFiddle:http://jsfiddle.net/8p2yc/(这里有一个稍微修改过的例子:http://bl.ocks.org/mbostock/3883245 )

正如您在JSFiddle中看到的那样,沿y轴的刻度标签不适合svg.我知道我可以增加左边距,但问题是我不知道预先提供了什么数据.如果我只是使边距非常大,如果数字很短,图表看起来会很尴尬.

有没有办法在创建图表时预先计算最大标签宽度以正确设置边距?或许还有一个完全不同的解决方案?

var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 400 - margin.left - margin.right,
    height = 200 - margin.top - margin.bottom;

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
Run Code Online (Sandbox Code Playgroud)

示例图表

谢谢!

Lar*_*off 15

您可以通过附加最大标签的文本,测量它并在之后立即将其删除来完成此操作:

var maxLabel = d3.max(data, function(d) { return d.close; }),
    maxWidth;
svg.append("text").text(maxLabel)
   .each(function() { maxWidth = this.getBBox().width; })
   .remove();
Run Code Online (Sandbox Code Playgroud)

然后您可以使用该宽度来执行g元素的转换:

svg.attr("transform", "translate(" + Math.max(margin.left, maxWidth) + "," + margin.top + ")");
Run Code Online (Sandbox Code Playgroud)

在这里完成示例.

编辑:获取实际标签的最大长度需要更多参与,因为您必须生成它们(使用正确的格式)并测量它们.当你测量实际显示的内容时,这是一种更好的方法.代码类似:

var maxWidth = 0;
svg.selectAll("text.foo").data(y.ticks())
   .enter().append("text").text(function(d) { return y.tickFormat()(d); })
   .each(function(d) {
     maxWidth = Math.max(this.getBBox().width + yAxis.tickSize() + yAxis.tickPadding(), maxWidth);
   })
 .remove();
Run Code Online (Sandbox Code Playgroud)

我在这里添加了刻度线的大小和刻度线和标签之间的填充.这里有完整的例子.