Chartjs-Unique identifier in Chartjs Bar segments?

0👍

First it worth to mention the version that you are using is the old 1.1.

You have a couple of problems here, to change the chart type you will first need to change how you set the pieData variable, after that the getSegmentsAtEvent event only works with the pie type, the proper event is getBarsAtEvent.

Here is an working example (please note that I haven’t used the original chart data):

Chart.types.Bar.extend({
  name: "PieUnique",
  addData: function(segment, atIndex, silent) {
    var index = atIndex || this.segments.length;
    this.segments.splice(index, 0, new this.SegmentArc({
      value: segment.value,
      outerRadius: (this.options.animateScale) ? 0 : this.outerRadius,
      innerRadius: (this.options.animateScale) ? 0 : (this.outerRadius / 100) * this.options.percentageInnerCutout,
      fillColor: segment.color,
      highlightColor: segment.highlight || segment.color,
      showStroke: this.options.segmentShowStroke,
      strokeWidth: this.options.segmentStrokeWidth,
      strokeColor: this.options.segmentStrokeColor,
      startAngle: Math.PI * this.options.startAngle,
      circumference: (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
      label: segment.label,
      //add option passed
      id: segment.id
    }));
    if (!silent) {
      this.reflow();
      this.update();
    }
  },
});

var pieData = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
      label: "My First dataset",
      fillColor: "rgba(220,220,220,0.5)",
      strokeColor: "rgba(220,220,220,0.8)",
      highlightFill: "rgba(220,220,220,0.75)",
      highlightStroke: "rgba(220,220,220,1)",
      data: [65, 59, 80, 81, 56, 55, 40]
    },
    {
      label: "My Second dataset",
      fillColor: "rgba(151,187,205,0.5)",
      strokeColor: "rgba(151,187,205,0.8)",
      highlightFill: "rgba(151,187,205,0.75)",
      highlightStroke: "rgba(151,187,205,1)",
      data: [28, 48, 40, 19, 86, 27, 90]
    }
  ]
};

var ctx = document.getElementById("chart-area").getContext("2d");
window.myPie = new Chart(ctx).PieUnique(pieData);

document.getElementById("chart-area").onclick = function(evt) {
  var activePoints = window.myPie.getBarsAtEvent(evt);

  if (activePoints[0]) {
    var label = activePoints[0].label;
    var value = activePoints[0].value;
    var id = activePoints[0].id;

    alert('label = ' + label + '   |   value = ' + value + '   |   id = ' + id);
  }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.min.js"></script>
<canvas id="chart-area"></canvas>

Leave a comment