| commit | author | age | ||
| 83c3f6 | 1 | # Mixed Chart Types |
| SP | 2 | |
| 3 | 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. | |
| 4 | ||
| 5 | Creating a mixed chart starts with the initialization of a basic chart. | |
| 6 | ||
| 7 | ```javascript | |
| 8 | var myChart = new Chart(ctx, { | |
| 9 | type: 'bar', | |
| 10 | data: data, | |
| 11 | options: options | |
| 12 | }); | |
| 13 | ``` | |
| 14 | ||
| 15 | At this point we have a standard bar chart. Now we need to convert one of the datasets to a line dataset. | |
| 16 | ||
| 17 | ```javascript | |
| 18 | var mixedChart = new Chart(ctx, { | |
| 19 | type: 'bar', | |
| 20 | data: { | |
| 21 | datasets: [{ | |
| 22 | label: 'Bar Dataset', | |
| 23 | data: [10, 20, 30, 40] | |
| 24 | }, { | |
| 25 | label: 'Line Dataset', | |
| 26 | data: [50, 50, 50, 50], | |
| 27 | ||
| 28 | // Changes this dataset to become a line | |
| 29 | type: 'line' | |
| 30 | }], | |
| 31 | labels: ['January', 'February', 'March', 'April'] | |
| 32 | }, | |
| 33 | options: options | |
| 34 | }); | |
| 35 | ``` | |
| 36 | ||
| 37 | At this point we have a chart rendering how we'd like. It's important to note that the default options for a line chart are not merged in this case. Only the options for the default type are merged in. In this case, that means that the default options for a bar chart are merged because that is the type specified by the `type` field. | |
| 38 | ||
| 39 | {% chartjs %} | |
| 40 | { | |
| 41 | "type": "bar", | |
| 42 | "data": { | |
| 43 | "labels": [ | |
| 44 | "January", | |
| 45 | "February", | |
| 46 | "March", | |
| 47 | "April" | |
| 48 | ], | |
| 49 | "datasets": [{ | |
| 50 | "label": "Bar Dataset", | |
| 51 | "data": [10, 20, 30, 40], | |
| 52 | "borderColor": "rgb(255, 99, 132)", | |
| 53 | "backgroundColor": "rgba(255, 99, 132, 0.2)" | |
| 54 | }, { | |
| 55 | "label": "Line Dataset", | |
| 56 | "data": [50, 50, 50, 50], | |
| 57 | "type": "line", | |
| 58 | "fill": false, | |
| 59 | "borderColor": "rgb(54, 162, 235)" | |
| 60 | }] | |
| 61 | }, | |
| 62 | "options": { | |
| 63 | "scales": { | |
| 64 | "yAxes": [{ | |
| 65 | "ticks": { | |
| 66 | "beginAtZero": true | |
| 67 | } | |
| 68 | }] | |
| 69 | } | |
| 70 | } | |
| 71 | } | |
| 72 | {% endchartjs %} | |