2017-01-23 48 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/ –