在c3.js中获取x轴值以自定义工具提示?

马希尔

我正在尝试在c3折线图中编辑工具提示。具体来说,我需要访问chart.tooltip.format.value函数中的当前x值但是,该函数未显式传递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'
            }
        },
    },

});
斯堪的雷特

您可以使用工具提示的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/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章