2017-01-23 126 views
1

我在编辑c3线图中的工具提示。具体来说,我需要访问chart.tooltip.format.value函数中的当前x值。但是,函数不会显式传递x值。在c3.js中获取x轴值以定制工具提示?

var chart = c3.generate({ 
    tooltip: { 
     format: { 
      value: function (value, ratio, id, index) { 
       return value; 
      } 
     } 
    }, 

    data: { 
     x: 'YEAR', 
     xFormat: '%Y', 
     url: myURL', 
    }, 
    axis: { 
     x: { 
      type: 'timeseries', 
      tick: { 
       format: '%Y' 
      } 
     }, 
    }, 

}); 

回答

1

您可以使用工具提示的contents属性来创建一个自定义的工具提示,并在那里,你可以通过访问X值:d[0].x

编辑:使用d[0].x.getFullYear()仅检索日期的年份部分(这是一个时间序列,从而C3内部存储所提供的一年,一个javascript日期对象)

这里的代码中,我从这个讨论采取https://github.com/c3js/c3/issues/444和改性:

function tooltip_contents(d, defaultTitleFormat, defaultValueFormat, color) { 
    var $$ = this, config = $$.config, CLASS = $$.CLASS, 
     titleFormat = config.tooltip_format_title || defaultTitleFormat, 
     nameFormat = config.tooltip_format_name || function (name) { return name; }, 
     valueFormat = config.tooltip_format_value || defaultValueFormat, 
     text, i, title, value, name, bgcolor; 

    // You can access all of data like this: 
    //console.log($$.data.targets); 

    for (i = 0; i < d.length; i++) { 
     if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; } 

     // to exclude 
     //if (d[i].name === 'data2') { continue; } 

     if (! text) { 
      title = 'MY TOOLTIP @ ' + d[0].x.getFullYear(); // SHOW X-VALUE, year only (given it is a time series) 
      text = "<table class='" + CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : ""); 
     } 

     name = nameFormat(d[i].name); 
     value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index); 
     bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id); 

     text += "<tr class='" + CLASS.tooltipName + "-" + d[i].id + "'>"; 
     text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>"; 
     text += "<td class='value'>" + value + "</td>"; 
     text += "</tr>";    
    } 

    return text + "</table>";  
} 

var chart = c3.generate({ 
    data: { 
     x: 'year', 
     xFormat: '%Y', 
     columns: [ 
      ['year', '1970', '1975', '1980', '1985', '1990'], 
      ['data1', 100, 200, 150, 300, 200], 
      ['data2', 400, 500, 250, 700, 300], 
     ] 
    }, 
     axis: { 
     x: { 
      type: 'timeseries', 
      tick: { 
       format: '%Y' 
      } 
     }, 
    }, 

    tooltip: { 
     contents: tooltip_contents 
    } 
}); 

我的拨弄,显示当前的x值:http://jsfiddle.net/w7h385h3/5/

+0

感谢您的代码。但是,x值(从csv加载)是几年,例如'1970'。但是'd [i] .x'中的值被格式化为'Thur Jan 01 1970 00:00:00 GMT-0800(PST)' – Mahir

+0

而不覆盖工具提示属性,标题正确显示为'1970' – Mahir

+0

这是因为你指定'xFormat:'%Y''只返回年份。它在内部应用。我已经用时间序列和javascript日期对象更新了代码,并且只显示了年份 - http://jsfiddle.net/w7h385h3/4/ –

相关问题