Hi, guys, welcome back to Appsloveworld. In our previous article, we learned about creating a Multi-Line Chart Using Chart.js in detail. And now in this article, we are going to talk about another striking feature of Chart Js i.eHow we can create a Vertically stacked bar chart with chart.js.
A stacked bar chart is a very important and useful chart that uses bars to show comparisons between different types of data, but with the capability to break down and compare parts of a whole data. Each bar in the graph represents a whole or complete, and parts in the bar represent different parts that total data.
Stacked bar charts Example with different values in stacks
Simply I have created an HTML page and added the latest chart js CDN reference to our Html page. and On our page, we have a Canvas element for creating the Stacked Barchart.
Recently I’m working on a project in which we need to create a stacked bar chart for that I was looking for an Excellent and free open source library. and then come across the Chart.js. We are changing our charts from paid charts library to open source chart.js, as we know that we can use chart js offline mode also and responsive to window’s changes of size.
I’ve been reading the documentation regarding, In all examples, I notice for stacked bar charts, the number of items in a bar is the same for each bar in the graph.
But our requirement is different and I can’t figure out, how to make a stacked bar chart like the below image example 2. after some brainstorming, I find out solution which I will share in this article. So in this article, we will provide you with two examples.
In our first example we are going to create a stacked bar chart just like google analytics like the below image, we are going to create a visitors bar chart with included values from various sources like organic search, social media search, paid search.
Let’s say we have been asked to create a bar graph to illustrate the visitor to your website. Specifically, you should show how many visitors from each of the following four sources i.e Organic terrific, Social terrific, Referral terrific, and Paid terrific from the ad campaign.
we need to show how many of the users are coming from Organic terrific and how many are coming from another channel. we can combine the information into a stacked bar chart.
<!DOCTYPE html>
<html>
<head>
<title>Create stacked bar chart using chart.js</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
</head>
<body>
<div style="margin-left:5%;margin-right:5%">
<canvas id="StackedbarChartcanvas" style="width:80%"></canvas>
</div>
<script>
var StackedbarChart = {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"June",
"July",
"Aug",
"Sep",
"Oct"
],
datasets: [
{
label: "Oraganic Search",
backgroundColor: "red",
borderColor: "red",
borderWidth: 1,
data: [42, 56, 26, 52, 66, 87, 51, 42, 32, 88]
},
{
label: "Soical Media",
backgroundColor: "blue",
borderColor: "blue",
borderWidth: 1,
data: [120, 52, 69, 62, 12, 45, 110, 52, 39, 75]
},
{
label: "Paid Search",
backgroundColor: "lightblue",
borderColor: "lightblue",
borderWidth: 1,
data: [45, 88, 112, 41, 48, 69, 52, 61, 59, 69]
}
]
};
var StackedbarChartOptions = {
responsive: true,
plugins: {
legend: {
position: 'right',//this option is used for place legend on the right side of bar chart
},
scales: {
x: {
stacked: true,// this option is used to make the bars stacked
},
y: {
stacked: true
}
},
title: {
display: true,
text: "Chart.js Stacked Bar Chart"
}
}
}
window.onload = function () {
var chartData = {
type: "bar",
data: StackedbarChart,
options: StackedbarChartOptions
}
new Chart("StackedbarChartcanvas", chartData);
};
</script>
</body>
</html>
Codepen Editor
Vertical stacked bar chart with chart.js
In this example, we will create a Vertically stacked bar chart with chart.js with a different item in each bar like the below image. I want to show a bar chart of total daily users on the website, and that bar should contain info of visitors from all sources.
<!DOCTYPE html>
<html>
<head>
<title>Create stacked bar chart with different item in each bar using chart.js</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
</head>
<body>
<div style="margin-left:5%;margin-right:5%">
<canvas id="StackedbarChartcanvas" style="width:80%"></canvas>
</div>
<script>
var StackedbarChart = {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"June",
"July",
"Aug",
"Sep",
"Oct"
],
datasets: [
{
label: "Organic terrific",
backgroundColor: "red",
borderColor: "red",
borderWidth: 1,
data: [42, 56, 0, 52, 66, 87, 51, 42, 32, 88]
},
{
label: "Soical terrific",
backgroundColor: "blue",
borderColor: "blue",
borderWidth: 1,
data: [0, 52, 94, 62, 12, 45, 110, 52, 39, 75]
},
{
label: "Referral terrific",
backgroundColor: "green",
borderColor: "green",
borderWidth: 1,
data: [0, 12, 0, 23, 87, 92, 63, 47, 29, 79]
},
{
label: "Paid terrific",
backgroundColor: "lightblue",
borderColor: "lightblue",
borderWidth: 1,
data: [45, 88, 0, 41, 48, 69, 52, 61, 59, 69]
}
]
};
var StackedbarChartOptions = {
responsive: true,
plugins: {
legend: {
position: 'right',//this option is used for place legend on the right side of bar chart
}
},
scales: {
x: {
stacked: true,// this option is used to make the bars stacked
},
y: {
stacked: true
}
},
title: {
display: true,
text: "Chart.js Stacked Bar Chart"
}
}
window.onload = function () {
var chartData = {
type: "bar",
data: StackedbarChart,
options: StackedbarChartOptions
}
new Chart("StackedbarChartcanvas", chartData);
};
</script>
</body>
</html>
*Thank you so much if you have a question please comment
The post How to Create a Stacked Bar Chart Using Chart Js Example? appeared first on Software Development | Programming Tutorials.
Read More Articles
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- An Image Alignment Issue
- label animation on interval
- Change a URL in a AJAX call using jQuery
- Making Javascript resizable handlers on the borders of HTML elements
- Remove table row if mapped td equals something
- css show and slide div on hover wrapper
- How do I properly get the mouse position in Javascript?
- jQuery Maximum call stack size exceeded, when focusing on next input field
- Codeigniter - Posting form variables and retrieving through jQuery AJAX
- Need a mapping of parent and child div ids
- Is that possible to trigger a jquery plugin function from a vuejs method?
- How to properly export and process data from editable table
- jquery scroll the height of hovered div
- Threshold value change on click of rangeSelector in HighStock graph
- set-cookies in response headers is 'half' working
- Smooth scroll not working on a tag inside p tag
- jQuery: find siblings under varying depth
- Call for another ajax from the result one ajax request got
- Not getting the closest to 0 result
- How to make dot-navigation on a swipe list
- input data to draggable not working
- Web Service call fails from JQuery
- Ajax updatet score from input value
- Removing # and its value from url
- Return array from $.get() in nested loops
- JS greeter not working
- JavaScript code outputs twice when clicking submit button
- How to populate a form field using jQuery
- passing variables from a javascript file to another html page
- find an element with jquery
- Check if href linked page exists
- convert time string to seconds in javascript/jquery
- Using jquery/JS/CSS how do I append words to a sentence so the sentence is pushed up word by word
- jQuery Document Ready Hover Detection
- Play a keyframe animation on first click and play back in reverse on second
- How to get autocomplete search when select data in dropdown box
- Jquery autocomplete suggestion is not showing under textbox and showing at the bottom of the page in ASP.NET MVC
- How is the scrolling functionality done in this website?
- on fadeout completed check if item exists
- Jdewit Timepicker show widget on text and icon click
- jquery scrolling function not working properly
- jquery onclick id & values of html elements
- I can get the next button to work but not the previous button. What am I doing wrong?
- JQuery Navigation Sticky
- Find the selected tab index/name
- Twitch live status of each username on the page
- Get the value of dropdown from parent with in a iframe using jQuery
- Cant bind line Flot Chart
- jQuery & Audio API - skip to certain part with .click
- Trying to make a rectangle move in canvas when a key is pressed but it will not work
- How to reduce website load time
- Target Only Safari in Javascript
- Animating a group of objects with jquery .each()
- DataTables + input checkboxesdon't work
- Backbone render external template without $.get
- twitter bootstrap dropdown in navigation not working
- how to Display specific months in boostrap datepicker
- JavaScript format date like in PHP
- Javascript variable cut off after apostrophe
- Navigation bar doesn't respond on mobile devices
- Is it possible to change row position of a table
- get value from a div or any container in angularjs
- Fullcalendar refresh/reredenred all events
- Creating and Populating JSON Object with jQuery via Loops
- Selector inside Selector passing parameter, JQuery Code to Dojo
- jQuery function not working: selecting different elements in same class
- jQuery Validation on a static form
- Cannot initiate a simple Supersized in Magento
- How to Write PHP in AJAX
- How do I close the input if submit is clicked
- jQuery - $(this) on iPad
- Is it possible to manipulate the target window of a form using Jquery
- Google Map does not display the whole map
- jQuery mouseover from an array
- $.extend property not working
- pause all videos on page while current one is playing
- Image Slider buttons not firing
- PHP $_POST receives no data
- jQuery: Index of element ignoring selector
- How do I write this jQuery more efficiently?
- How to save a refernece to a checkbox in a table row?
- SlideUp Slide Down from multiple radio buttons
- Is it possible to open a modal on input focus and enter a value to the input from the modal?
- hashchange prevents scrolling to targeted div
- custom keyboard shortcuts using javascript for web app
- Jquery Validation, open accordion
- jquery not unbinding a "resize" bind done in a plugin
- concat javascript with cakephp
- jquery interval impulse appointing a new random instead of checking the correct answer
- Trying to calculate sum only when shown based on value in td marked with id with javascript/jquery
- UIKIT Lightbox Javascript Close
- call jquery inside php
- Using Select2 in dropdownlist
- Running jQuery animations in unison
- Looping an Array in jQuery to change CSS
- Passing variable from one PHP page to another without refreshing
- Event after option from dropdown menu is chosen
- Access ASP.NET controls dynamic client ID in jQuery
- Fancybox: Prepend each relative html content from a list
- Embed HTML with Style in Angular JS
- Change select options on onload
- Define randomisation ratio in javascript
- Perform an AJAX call using Django Form
- One function is running for all div containing same class. How can i get rid of it?
- How to Remove/Empty Sibling in JQuery & Append
- How To Get unique id number
- Reverting Back to Inline Style on Button Click - jQuery
- Clone table row and increment input name
- Obtain key value in for each in Javascript like PHP
- Convert JSON structure using javascript
- Override settings of jQuery plugin?
- Ajax/Javascript User Status update
- Override Date Object Error: "this is not a Date object."
- Assigning an ajax fetch function to a variable returns undefined even though data definitely returns?
- Property is not defined
- Bootstrap datepicker show dates only
- Iterate and retrieve data from database
- jquery from base.html not working in other templates in django
- What happens to jquery event handlers after element removal?
- jQuery $.get() Order Doesn't Match
- Scroll datetimepicker jQuery
- In a grid built in javascript and html, how do I assign a new text-node value to all cells in the grid that fulfils a condition
- Graph/Chart suggestions. Using PHP, jQuery - silverlight?
- Highstock - Tooltip doesn't work correctly with Range Selector
- Set value of div to shown/hidden after POST based on value of drop down list
- Jquery getting position().top of div with :not(.class)
- Should I obfuscate my plugin before sharing with others?
- Store input's value as a variable to used in an equation
- Submit form refresh the page
- How to handle visibility of div only by clicking of particular div
- How to fix navigation bar
- jQuery UI autocomplete values in a horizontal list
- php sql Get query when checkbox is checked
- Jquery attr change structure html
- Highchart: Plot negative values on negative Y Axis ans set initial value
- How to create an HTML bookmark anchor for a JavaScript tab
- using load() to load page that also uses jQuery
- Validate file size and type in a multiple input
- How to define On Change function dynamically using loops in JQuery?
- Hyperlink JQuery doesn't triggered
- Prefilled the form data from the another page's input
- how to make a modal disappear if it is clicked outside
- Removing div rows which have same class identifiers dynamically
- Using .addClass after 0 seconds, rather than 10, if HTML element doesn't exist
- Question about cache in javascript/jquery
- TypeError: sportsRecord.find is not a function
- Convert string into an array
- jqgrid hide columns on edit form based on an other column value
- Running an animation after a set time using animate.css
- Add select2 data and date format to database with php