How to get Combined Bar and Line Charts ?
Chart.js provides features to combine different types of charts, such as bar and line charts, in a single graph. By using this feature you can present complex data sets in a more comprehensive and meaningful way. In this article, we will learn about how to combine a Bar and Line chart.
To combine the bar and the line chart, you can use an array to set the dataset property of the chart where each array item will contain a different chart type and its chart.
Chart.js CDN link
Before we get started make sure you have included this CDN link of chart.js in a head section of your HTML code:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
Syntax:
const mixedChart = new Chart(canvas_element , {
// The default chart type for the graph
type: 'bar',
data: {
//Label Array
labels: [...],
datasets: [
{
type: 'bar',
// data of the chart....
},
{
type: 'line',
// data of the chart....
},
]
}
});
Example: The below code example will show you how you can get the combiined bar and line charts in chart.js.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0"> < script src = "https://cdn.jsdelivr.net/npm/chart.js" > </ script > < title > Mixed Chart Example </ title > < style > div { height: 50vh; width: 50vw; } </ style > </ head > < body > < h1 > w3wiki | Mixed Chart </ h1 > < div > <!-- Create a canvas element to render the chart --> < canvas id = "mixedChart" width = "400" height = "200" > </ canvas > </ div > < script > // Get the 2D rendering // context of the canvas const ctx = document. getElementById('mixedChart'). getContext('2d'); // Create a new Chart instance with // a default chart type of 'bar' const mixedChart = new Chart(ctx, { // The default chart // type for the graph type: 'bar', data: { // Labels for the X-axis labels: ['January', 'February', 'March', 'April', 'May'], // Datasets for the chart datasets: [{ //Chart type type: 'bar', // Label for the dataset label: 'Pizza bar chart', // Data points for the Y-axis data: [122, 77, 45, 104, 66], // Background color for the bars backgroundColor: 'rgba(215, 153, 20, 0.5)', // Border color for the bars borderColor: 'rgba(215, 153, 20, 1)', // Border width for the bars borderWidth: 1 }, { type: 'line', label: 'Pizza line chart', data: [122, 77, 45, 104, 66], borderColor: 'rgba(215, 153, 20, 1)', }, { type: 'bar', label: 'Burger bar chart', data: [87, 133, 87, 66, 84], backgroundColor: 'rgba(75, 192, 192, 0.5)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }, { type: 'line', label: 'Burger line chart', data: [87, 133, 87, 66, 84], borderColor: 'rgba(75, 192, 192, 1)', }] }, options: { // It makes the chart responsive responsive: true, // This plugin will display Title of chart plugins: { title: { display: true, text: 'Monthly Sales of Pizza and Burger' } } } }); </ script > </ body > </ html > |
Output:
Contact Us