2016-11-21 16 views
0

我有一个条形图,其中包含沿x轴的日期。我定义x轴是这样的:如何在工具提示中放置日期时仅显示轴的一部分与日期一起显示?使用D3.js

var xAxis = d3.svg.axis() 
      .scale(xScale) 
      .orient("bottom") 
      .ticks(d3.time.months, 1) 
      .tickSize(0) 
      .tickFormat(RU.timeFormat("%b %Y")); 

之后,我拿起从轴文本的日期,并把它们放在提示。通过这种方式:

.on("mouseover", function(d, i) { 
     var tickDate = d3.select(d3.selectAll(".axis .tick text")[0][i]).data()[0]; 
     var formatDate = RU.timeFormat("%B %Y"); 
     var tooltipDate = formatDate(tickDate); 

而且一切都确定了这种做法,直到我改变了这一行中的日期刻度线的频率:

.ticks(d3.time.months, 2) 

该提示的一部分消失后。我该如何解决这个错误? 我的jsfiddle:https://jsfiddle.net/anton9ov/cLb1nxwj/

回答

0

的问题是在鼠标悬停在您尝试将数据与日期结合: var tickDate = d3.select(d3.selectAll(".axis .tick text")[0][i]).data()[0]; ,然后尝试得到正确的日期

// here d3.selectAll(".axis .tick text")[0][i] fails and returns undefined 
// because i is out of range since there are more data than months 
var tickDate = d3.select(d3.selectAll(".axis .tick text")[0][i]).data()[0]; 
var formatDate = RU.timeFormat("%B %Y"); 
// so formatDate fails when trying to format an empty value 
var tooltipDate = formatDate(tickDate); 

你可以尝试这样的事: https://jsfiddle.net/b03prLm8/5/

其中:

// you get your dates with length 10 
    var dates = d3.selectAll(".axis .tick text")[0]; 

    // Since it is two values per date - with one exception see below 
    // check if the current value's modulo with two (the ticks freq.) is zero 
    // if not, use ceil to get the correct bin/ date the value belongs 
    // e.g. if i is 9, then 9/2=4.5 becomes 4, so 9 belongs to the 4th date 
    // and so on... 
    var index = (i % 2 == 0) 
         ? i/2 
         : Math.ceil(i/ 2); 

    if(index > 0) index -= 1; // because the first bar is not within the dates range 
    // then go on as usual 
    var tickDate = d3.select(dates[index]).data()[0]; 
    var formatDate = RU.timeFormat("%B %Y"); 
    var tooltipDate = formatDate(tickDate); 

希望这会有所帮助。祝你好运!

相关问题