javascript – 如何在D3线图上设置可变长度刻度标签?

这是一个JSfiddlehttp://jsfiddle.net/8p2yc/(从这里稍稍修改的例子: http://bl.ocks.org/mbostock/3883245)

正如你可以在JSfiddle中看到的,沿着y轴的标签不符合svg.我知道我可以增加左边距,但事实是我不知道预先提供的数据.如果我只是使边框非常大,如果数字短,图表会看起来很尴尬.

创建图表时是否有预先计算最大标签宽度以便正确设置边距的方法?或者也许有一个完全不同的解决方案?

var margin = {top: 20,right: 20,bottom: 30,left: 50},width = 400 - margin.left - margin.right,height = 200 - margin.top - margin.bottom;

var svg = d3.select("body").append("svg")
    .attr("width",width + margin.left + margin.right)
    .attr("height",height + margin.top + margin.bottom)
  .append("g")
    .attr("transform","translate(" + margin.left + "," + margin.top + ")");

谢谢!

解决方法

您可以通过附加最大标签的文本进行测量,然后立即将其删除
var maxLabel = d3.max(data,function(d) { return d.close; }),maxWidth;
svg.append("text").text(maxLabel)
   .each(function() { maxWidth = this.getBBox().width; })
   .remove();

然后可以使用该宽度来进行g元素的翻译:

svg.attr("transform","translate(" + Math.max(margin.left,maxWidth) + "," + margin.top + ")");

完成例here.

编辑:获取实际标签的最大长度有一点参与,因为您必须生成它们(使用正确的格式)并测量它们.这是一个更好的方式来做,虽然,因为你正在测量实际显示.代码相似:

var maxWidth = 0;
svg.selectAll("text.foo").data(y.ticks())
   .enter().append("text").text(function(d) { return y.tickFormat()(d); })
   .each(function(d) {
     maxWidth = Math.max(this.getBBox().width + yAxis.tickSize() + yAxis.tickPadding(),maxWidth);
   })
 .remove();

我将滴答线的大小和刻度线和标签间的填充添加到此处的宽度. here的完整例子.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...