Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create single value Doughnut or Pie chart using Chart.js? [closed]

Is there a way to create chart like this using Chart.js

enter image description here

like image 372
Syed Avatar asked Feb 12 '18 14:02

Syed


People also ask

How do you make a donut pie graph?

Select the data that you want to plot in the doughnut chart. On the Insert tab, in the Charts group, click Other Charts. Under Doughnut, click Doughnut. Click the plot area of the doughnut chart.

What is CTX in chart js?

js convention is to call it ctx . An object literal containing the data and the configuration options that Chart. js will use to build your chart. The required properties are type and data . In our example type is 'line' because we want a line chart.


1 Answers

Here is an example:

var value = 75;
var data = {
  labels: [
    "My val",
    ""
  ],
  datasets: [
    {
      data: [value, 100-value],
      backgroundColor: [
        "#FF6384",
        "#AAAAAA"
      ],
      hoverBackgroundColor: [
        "#FF6384",
        "#AAAAAA"
      ],
      hoverBorderColor: [
        "#FF6384",
        "#ffffff"
      ]
    }]
};

var myChart = new Chart(document.getElementById('myChart'), {
  type: 'doughnut',
  data: data,
  options: {
  	responsive: true,
    legend: {
      display: false
    },
    cutoutPercentage: 80,
    tooltips: {
    	filter: function(item, data) {
        var label = data.labels[item.index];
        if (label) return item;
      }
    }
  }
});

textCenter(value);

function textCenter(val) {
  Chart.pluginService.register({
    beforeDraw: function(chart) {
      var width = chart.chart.width,
          height = chart.chart.height,
          ctx = chart.chart.ctx;

      ctx.restore();
      var fontSize = (height / 114).toFixed(2);
      ctx.font = fontSize + "em sans-serif";
      ctx.textBaseline = "middle";

      var text = val+"%",
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = height / 2;

      ctx.fillText(text, textX, textY);
      ctx.save();
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>
like image 175
beaver Avatar answered Oct 01 '22 14:10

beaver