13

我正在用 d3 绘制折线图,​​一切正常。但是,我必须在图表区域的左侧留出足够的边距,以适应我认为可能是最宽 y 轴文本标签的任何内容。我想根据最宽的标签调整每个图表的空间。

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

但是,如果最大 y 值是“1598.538”,那么最上面的 y 轴标签可能是“1500”……也就是说,要窄得多。

所以我想我想找到实际上是最顶层标签的宽度。但是如果不绘制图表和轴,测量宽度并再次真实绘制,我无法想到如何做到这一点。听起来很恶心!有没有一种不讨厌的方法来做到这一点?

更新

这是我的代码的一部分,使用 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 + ")");
4

1 回答 1

6

您可以将所有内容放在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)");
于 2013-06-14T14:02:16.383 回答