[英]Set y-axis of d3 chart to fit widest label?
I'm drawing line charts with d3 and it all works fine. 我正在用d3绘制折线图,并且一切正常。 However, I have to leave enough margin on the left of the chart area to fit whatever I think might be the widest y-axis text label. 但是,我必须在图表区域的左侧保留足够的边距,以适合我认为可能是最宽的y轴文本标签的内容。 I'd like to adjust this space for each chart, depending on the widest label. 我想为每个图表调整此空间,具体取决于最宽的标签。
Initially I thought I could find the maximum y value, create a hidden text object, work out how wide that is, and use that value for the left margin when creating the chart. 最初,我以为我可以找到y的最大值,创建一个隐藏的文本对象,计算出它的宽度,并在创建图表时使用该值作为左边距。 A bit nasty, but it gets me a value. 有点讨厌,但它给我带来了价值。
However, if the maximum y value is, say "1598.538" the top-most y-axis label might be "1500"... ie, a lot narrower. 但是,如果最大y值是“ 1598.538”,则最顶部的y轴标签可能是“ 1500” ...,即,窄得多。
So I guess I want to find the width of whatever will actually be the top-most label. 所以我想我想找到实际上将是最上面的标签的宽度。 But I can't think how to do that without drawing the chart and axis, measuring that width, and drawing it again for real. 但我想不出绘制图表和轴,测量该宽度并再次将其重新绘制成实线的方法。 Which sounds nasty! 听起来很讨厌! Is there a non-nasty way to do this? 有没有讨厌的方式来做到这一点?
UPDATE 更新
Here's part of my code, using Lars' suggestion, just to show where it fits in: 这是我的代码的一部分,使用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 + ")");
You can put everything inside a g
element and set transform
based on the max width. 您可以将所有内容放入g
元素内,并根据最大宽度设置transform
。 Something along the lines of 遵循以下原则
var maxw = 0;
yAxisContainer.selectAll("text").each(function() {
if(this.getBBox().width > maxw) maxw = this.getBBox().width;
});
graphContainer.attr("transform", "translate(" + maxw + ",0)");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.