[Chartjs]-Chart.js – Multiple Doughnut Charts on same Canvas

6👍

Have 2 canvas elements and position them one over the other using CSS. The inner canvas has the inner doughnut and has rounded borders so that it covers up as little of the outer doughnut as possible.


Preview

enter image description here


HTML

<div id="w">
    <canvas id="d1" height="400" width="400"></canvas>
    <canvas id="d2" height="320" width="320"></canvas>
</div>

CSS

#w {
    position: relative;
    height: 400px;
    width: 400px;
}

#d1, #d2 {
    position: absolute;
}

#d1 {
    top: 0px;
    left: 0px;
}

#d2 {
    border-radius: 150px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

Fiddle – https://jsfiddle.net/rhLxawt5/

At this point we have a reasonably decent looking pie chart with non overlapping doughnuts, however our tooltips will get clipped off because they are still part of their respective canvases.

We can work around this by writing a customTooltips function to use a div instead of drawing a rectangle within the canvas.

Fiddle – https://jsfiddle.net/rca0ync3/

6👍

You can use multiple datasets, checkout the Chart JS demo page:

http://www.chartjs.org/samples/latest/charts/doughnut.html

Also, here is an example with multiple datasets and multiple labels too:

https://jsfiddle.net/moe2ggrd/1/

The important part:

  ...
  var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ["Green", "Yellow", "Red", "Purple", "Blue"],
      datasets: [{
        data: [1, 2, 3, 4, 5],
        backgroundColor: [
          'green',
          'yellow',
          'red',
          'purple',
          'blue',
        ],
        labels: [
          'green',
          'yellow',
          'red',
          'purple',
          'blue',
        ]
      }, {
        data: [6, 7, 8],
        backgroundColor: [
          'black',
          'grey',
          'lightgrey'
        ],
        labels: [
          'black',
          'grey',
          'lightgrey'
        ],
      }, ]
    },
    ...

Hope it helps someone who’s trying to do the same thing.

Leave a comment