您可以使用工具提示的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/
感謝您的代碼。但是,x值(從csv加載)是幾年,例如'1970'。但是'd [i] .x'中的值被格式化爲'Thur Jan 01 1970 00:00:00 GMT-0800(PST)' – Mahir
而不覆蓋工具提示屬性,標題正確顯示爲'1970' – Mahir
這是因爲你指定'xFormat:'%Y''只返回年份。它在內部應用。我已經用時間序列和javascript日期對象更新了代碼,並且只顯示了年份 - http://jsfiddle.net/w7h385h3/4/ –