设置d3图表的y轴以适应最宽的标签?

Phi*_*ord 10 javascript label linechart d3.js

我用d3画线图,一切正常.但是,我必须在图表区域的左侧留下足够的边距,以适应我认为可能是最宽的y轴文本标签.我想根据最宽的标签调整每个图表的空间.

最初我以为我可以找到最大的y值,创建一个隐藏的文本对象,计算出它的宽度,并在创建图表时将该值用于左边距.有点讨厌,但它让我有价值.

但是,如果最大y值是,例如"1598.538",则最顶部的y轴标签可能是"1500"......即,要窄得多.

所以我想我想找到实际上最顶级标签的宽度.但是我不知道如何在不绘制图表和轴的情况下做到这一点,测量宽度,并再次绘制它.这听起来很讨厌!有一种非讨厌的方法吗?

UPDATE

这是我的代码的一部分,使用Lars的建议,只是为了显示它适合的位置:

// I did have
// `.attr("transform", "translate(" + margin.left + "," + margin.top ")")`
// on the end of this line, but I've now moved that to the bottom.
var g = svg.select("g");

// Add line paths.
g.selectAll(".line").data(data)
    .enter()
    .append("path")
    .attr("d", line);

// Update the previously-created axes.
g.select(".axis-x")
    .attr("transform", "translate(0," + yScale.range()[0] + ")"))
    .call(xAxis);
g.select(".axis-y")
    .call(yAxis);

// Lars's suggestion for finding the maximum width of a y-axis label:
var maxw = 0;
d3.select(this).select('.axis-y').selectAll('text').each(function(){
  if (this.getBBox().width > maxw) maxw = this.getBBox().width;
});

// Now update inner dimensions of the chart.
g.attr("transform", "translate(" + (maxw + margin.left) + "," + margin.top + ")");
Run Code Online (Sandbox Code Playgroud)

Lar*_*off 5

您可以将所有内容放在g元素中,并transform根据最大宽度进行设置.有点像

var maxw = 0;
yAxisContainer.selectAll("text").each(function() {
    if(this.getBBox().width > maxw) maxw = this.getBBox().width;
});
graphContainer.attr("transform", "translate(" + maxw + ",0)");
Run Code Online (Sandbox Code Playgroud)