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

问题描述 投票:0回答:1

预先感谢大家:)

我想并排显示2个甜甜圈图,以比较2个不同年份的统计数据。我想要相同的密钥并将数据保留在相同的<canvas>中。

我不想:2个画布,该画布中有1个图表

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

我想要:1个画布,该画布中有2个图表

<canvas id="chart1"></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
    }
});
javascript chart.js
1个回答
0
投票

您可以在一页上使用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

© www.soinside.com 2019 - 2024. All rights reserved.