Mixed Chart Types

With Chart.js, it is possible to create mixed charts that are a combination of two or more different chart types. A common example is a bar chart that also includes a line dataset.

When creating a mixed chart, we specify the chart type on each dataset.

  1. var mixedChart = new Chart(ctx, {
  2. data: {
  3. datasets: [{
  4. type: 'bar',
  5. label: 'Bar Dataset',
  6. data: [10, 20, 30, 40]
  7. }, {
  8. type: 'line',
  9. label: 'Line Dataset',
  10. data: [50, 50, 50, 50],
  11. }],
  12. labels: ['January', 'February', 'March', 'April']
  13. },
  14. options: options
  15. });

At this point, we have a chart rendering how we’d like. It’s important to note that the default options for the charts are only considered at the dataset level and are not merged at the chart level in this case.

Mixed Chart Types - 图1

config setup

  1. const config = {
  2. type: 'scatter',
  3. data: data,
  4. options: {
  5. scales: {
  6. y: {
  7. beginAtZero: true
  8. }
  9. }
  10. }
  11. };
  1. const data = {
  2. labels: [
  3. 'January',
  4. 'February',
  5. 'March',
  6. 'April'
  7. ],
  8. datasets: [{
  9. type: 'bar',
  10. label: 'Bar Dataset',
  11. data: [10, 20, 30, 40],
  12. borderColor: 'rgb(255, 99, 132)',
  13. backgroundColor: 'rgba(255, 99, 132, 0.2)'
  14. }, {
  15. type: 'line',
  16. label: 'Line Dataset',
  17. data: [50, 50, 50, 50],
  18. fill: false,
  19. borderColor: 'rgb(54, 162, 235)'
  20. }]
  21. };

Drawing order

By default, datasets are drawn such that the first one is top-most. This can be altered by specifying order option to datasets. order defaults to 0. Note that this also affects stacking, legend, and tooltip. So it’s essentially the same as reordering the datasets.

  1. var mixedChart = new Chart(ctx, {
  2. type: 'bar',
  3. data: {
  4. datasets: [{
  5. label: 'Bar Dataset',
  6. data: [10, 20, 30, 40],
  7. // this dataset is drawn below
  8. order: 2
  9. }, {
  10. label: 'Line Dataset',
  11. data: [10, 10, 10, 10],
  12. type: 'line',
  13. // this dataset is drawn on top
  14. order: 1
  15. }],
  16. labels: ['January', 'February', 'March', 'April']
  17. },
  18. options: options
  19. });