我正在使用 d3 绘制折线图,一切正常。但是,我必须在图表区域的左侧留出足够的边距以适应我认为最宽的 y 轴文本标签。我想根据最宽的标签为每个图表调整此空间。
最初我以为我可以找到最大的 y 值,创建一个隐藏的文本对象,计算出它的宽度,并在创建图表时使用该值作为左边距。有点讨厌,但它给我带来了值(value)。
但是,如果最大 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 + ")");
最佳答案
您可以将所有内容放在 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)");
关于javascript - 设置 d3 图表的 y 轴以适合最宽的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17109549/