youi
youi

Reputation: 2047

Chartjs doughnut chart for conditional data

As i am pretty new to Charting libraries and in my case i have been asked to implement a Chartjs library for my requirement. So i have chosen a chartjs library. The use case i must want to know if anybody can help me then it would be a great time saver for me. Actually i am googleling since morning for this.

The actual use case is i have doughnut chart in which i am trying to show the data of a single value. As i have gone through the documentation the chartjs works on a array of data values. But my API is having only one value, means in my case its a counter variable. Assume if my maximum counter limit is say 5000 then i have to show that 5000 as a maximum counter and as the current counter is say 100 then i have to show it in the doughnut arc in red color. Means how much the graph has consumed the data something like that.

Assume total runs 5000 If runs became any count like 100 then we need to do minus from total runs - current runs count = 4900 inside the doughnut circle. As the runs increases then we need to show the reduced count runs inside the doughnut circle graph. Once if the current runs count comes to total runs the show the circle in red color and make the count to 0.

Is this possible using Chartjs? See below picture.

enter image description here

Upvotes: 0

Views: 2078

Answers (1)

Kunal Khivensara
Kunal Khivensara

Reputation: 1669

There is no built-in support for doing this in Chart.js, however, it can be achieved using a very simple hack. Look at the code and try to understand, if any issues feel free to comment.

I have used chartjs-datalabels plugin to show datalabels on the pieChart.

Hope it helps!

Fiddle -> http://jsfiddle.net/y6mnkz84/7/

  function drawPieChart(value, maxValue) {
  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ["Consumed"],
      datasets: [{
        data: [value, maxValue - value],
        backgroundColor: ['green', 'red'],
      }]
    },
    options: {
      tooltips: {
        enabled: false,
      },
      plugins: {
        datalabels: {
          backgroundColor: function(context) {
            return context.dataset.backgroundColor;
          },
          display: function(context) {
            var dataset = context.dataset;            
            var value = dataset.data[context.dataIndex];
            return value > 0;
          },
          color: 'white'
        }
      }
    }
  });
}


drawPieChart(5000, 5000);

Upvotes: 1

Related Questions