将d3图表的y轴设置为适合最宽的标签? [英] Set y-axis of d3 chart to fit widest label?

查看:63
本文介绍了将d3图表的y轴设置为适合最宽的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm drawing line charts with d3 and it all works fine. 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. I'd like to adjust this space for each chart, depending on the widest label.

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

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. A bit nasty, but it gets me a value.

但是,如果最大y值是"1598.538",则最上面的y轴标签可能是"1500" ...,也就是说,窄得多.

However, if the maximum y value is, say "1598.538" the top-most y-axis label might be "1500"... ie, a lot narrower.

所以我想我想找到实际上将是最上面的标签的宽度.但是,我不认为如何绘制图表和轴,测量宽度并再次将其重新绘制成真实的样子就可以做到这一点..................................................................................听起来很讨厌!有一种讨厌的方法吗?

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?

更新

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

Here's part of my code, using Lars' suggestion, just to show where it fits in:

// 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.类似于

You can put everything inside a g element and set transform based on the max width. 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)");

这篇关于将d3图表的y轴设置为适合最宽的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆