首页 文章

chart.js 2.0将新属性添加到数据集

提问于
浏览
0

我需要添加一个属性到数据集/标签,以便在点击时识别它 . 我尝试过这样的事情:

Chart.controllers.customBar = Chart.controllers.bar.extend({
        code: null
    });

它几乎可以工作,因为我可以看到新的属性“代码”,数据与它相关联,图表背景是可见的但是空的,我的意思是没有来自数据集的数据可见 .

这是我的初始化:

var ctx = document.getElementById("roads-chart").getContext("2d");
    window.roadsBar = new Chart(ctx, {
        type: 'bar',
        data: roadsChartData,
        options: {
            title: {
                display: true,
                text: "Stan dróg"
            },
            tooltips: {
                mode: 'label'
            },
            responsive: true,
            scales: {
                xAxes: [{
                        stacked: true,
                    }],
                yAxes: [{
                        stacked: true
                    }]
            },
            onClick: function(e, d) {
                console.log(d);
            }
        }
    });

问题是,我不觉得Chart.js,有人可以帮助我处理它并展示如何扩展工作的例子吗? :)

谢谢

1 回答

  • 0

    虽然您可以扩展图表来执行此操作,但如果您不介意依赖内部属性(可能在更高版本的chart.js中更改),您可以使用 _datasetIndex_index 属性从中检索您的额外属性 . 图表配置,就像这样

    options: {
        onClick: function(e, d) {
          if (d.length > 0) {
            console.log(this.config.data.datasets[d[0]._datasetIndex].code[d[0]._index]);
          }
        }
        ...
    

    ...
      datasets: [{
        code: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
        ...
    

    小提琴 - http://jsfiddle.net/55cdvb20/

相关问题