Charts.js DataIndex不会根据选定的数据集进行更新

时间:2017-09-15 08:35:56

标签: javascript chart.js

小提琴:Image File
你可以在这里看到我有3 dataindexes,即Hospital,Referral,Total。我在每个栏的顶部显示dataset 但是现在当我禁用一个dataIndexes时,dataset仍然适用于已停用的<div id="patientsBarGraphDiv" style="border: 1px solid black"> <canvas id="patientsBarGraph"></canvas> </div> var paitentData = { labels: ["Today", "Week", "Month", "Year"], datasets: [{ label: "Hospital Patients", fillColor: "#79D1CF", strokeColor: "#79D1CF", data:[ 24, 20, 30, 40] // adding data for the hospital section }, { label: "Referral Patients", fillColor: "#79D1CF", strokeColor: "#79D1CF", data:[ 14, 24, 34, 44] // adding data for referral section }, { label: "Total Patients", fillColor: "#79D1CF", strokeColor: "#79D1CF", data:[ 22, 32, 43, 52] // adding data for Total section } ] }; var opt = { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Patients Graph' }, hover: { animationDuration: 1 }, animation: { duration: 1, onComplete: function () { var chartInstance = this.chart, ctx = chartInstance.ctx; ctx.textAlign = 'center'; ctx.fillStyle = "rgba(0, 0, 0, 1)"; ctx.textBaseline = 'bottom'; this.data.datasets.forEach(function (dataset, i) { var meta = chartInstance.controller.getDatasetMeta(i); meta.data.forEach(function (bar, index) { var data = dataset.data[index]; ctx.fillText(data, bar._model.x, bar._model.y - 5); }); }); } } }; var ctx = document.getElementById("patientsBarGraph").getContext("2d");// getting the id of canvas var MyNewChart = new Chart(ctx,{ type: 'bar', data: paitentData, options:opt }); 。如何管理这个。请检查小提琴的运行代码 任何帮助将不胜感激。

{{1}}

1 个答案:

答案 0 :(得分:1)

forEach循环中添加以下代码行,以解决dataIndex更新问题:

var isDatasetVisible = chartInstance.controller.isDatasetVisible(i);
if (!isDatasetVisible) return;

以下是working example on JSFiddle