d3.js:从时间尺度获取刻度格式

smc*_*mcs 5 javascript d3.js

我正在使用d3构建时间轴可视化,其中域可以从几天到几十年不等.我正在使用d3时标和轴这样:

var timeScale = d3.time.scale()
    .domain([firstEvent, lastEvent])
    .range([leftPadding, w - rightPadding]);
var timeAxis = d3.svg.axis()
    .scale(timeScale)
    .orient("bottom");
timeAxis.ticks(5);
Run Code Online (Sandbox Code Playgroud)

由于域是如此可变,因此使用方便ticks(x),将自动选择刻度格式.我的问题是,在某些情况下,未显示年份,这是至关重要的.我的想法是在创建轴后检查刻度线格式,如果它不包含年份,则在轴旁边手动显示.但是,我无法获得比例尺的刻度格式; 使用timeScale.tickFormat()只返回一个函数.我怎么解决这个问题?

Mar*_*ark 4

一个简单的正则表达式测试怎么样?

var hasYear = false;
var re = /^\d{4}$/;
// get the ticks text    
d3.selectAll('.x>.tick>text').each(function(d){
  // does the text look like a year?
  var txt = this.textContent;
  if (re.test(txt)){
    hasYear = true;
  }
});
console.log(hasYear);
Run Code Online (Sandbox Code Playgroud)

使用此示例代码并尝试了各种范围:

var hasYear = false;
var re = /^\d{4}$/;
// get the ticks text    
d3.selectAll('.x>.tick>text').each(function(d){
  // does the text look like a year?
  var txt = this.textContent;
  if (re.test(txt)){
    hasYear = true;
  }
});
console.log(hasYear);
Run Code Online (Sandbox Code Playgroud)