简体   繁体   English

如何在一张图表中获得 2 个甜甜圈图 (chartjs)

[英]How to get 2 doughnut charts in one chart (chartjs)

Thanks in advance guys :)在此先感谢各位:)

I want to display 2 doughnut charts side by side to compare stats from 2 different years.我想并排显示 2 个圆环图以比较 2 个不同年份的统计数据。 I want to have the same key and keep the data in the same <canvas> .我想拥有相同的密钥并将数据保存在相同的<canvas>

I dont want: 2 canvas, 1 chart in the canvas我不想要:2 个画布,画布中的 1 个图表

<canvas id="chart1"></chart>
<canvas id="chart2"></chart>

I do want: 1 canvas, 2 charts in the canvas我确实想要:1 个画布,画布中有 2 个图表

<canvas id="chart1"></chart>

Here's some JS to add context, this data adds 1 chart.这里有一些 JS 来添加上下文,这个数据添加了 1 个图表。

var ctx = document.getElementById('chart1').getContext('2d');
var chart1 = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ['1', '2', '3'],
        datasets: [{
            label: 'Pie',
            data: [12, 9, 3],
            backgroundColor: [
               'rgb(0,51,10)',
               'rgb(02,11,191)',
               'rgb(98,18,08)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        cutoutPercentage: 75,
        responsive: false
    }
});

You can use 2 canvas on 1 page - see here:您可以在 1 页上使用 2 个画布 - 请参见此处:

<body>

<table border="1">
  <tr>
    <th>Chart1</th>
    <th>Chart2</th>
  </tr>
  <tr>
    <td>

     <div style="width: 50%">
    <canvas id="canvas1" height="450" width="600"></canvas>
     </div>

    </td>
    <td>

  <div style="width: 50%">
    <canvas id="canvas2" height="450" width="600"></canvas>
  </div>

    </td>
  </tr>
</table>


</body>

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
        {
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
        },  
            {
                label: '# of Points',
                data: [7, 11, 5, 8, 3, 7],
                borderWidth: 1
            }
        ]
  },
  options: {
    scales: {
        yAxes: [{
        ticks: {
                    reverse: false
        }
      }]
    }
  }
}
var options2 = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
        {
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
        },  
            {
                label: '# of Points',
                data: [7, 11, 5, 8, 3, 7],
                borderWidth: 1
            }
        ]
  },
  options: {
    scales: {
        yAxes: [{
        ticks: {
                    reverse: false
        }
      }]
    }
  }
}


var ctx = document.getElementById('canvas1').getContext('2d');
new Chart(ctx, options);
var ctx2 = document.getElementById('canvas2').getContext('2d');
new Chart(ctx2, options2);

fiddle小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM