There are many libraries out there that can help you visualize some data in your blog posts or presentations. One of the libraries you can use is Chart.js. Chart.js was created in 2013 by his London-based web developer Nick Downie. It is maintained by his second most popular JS charting library on GitHub. Chart.js is a free, open-source JavaScript library that is freely available to all users and helps plot data in web applications.
Chart.js supports the 8 chart types which are
Here is an example of a Bar Chart that is created using Chart.js:
Chart.js can be used with the HTML5 Canvas element. Canvas is an element that provides a simple and powerful way to draw graphics using JavaScript. You can use it to draw diagrams, create photo compositions, and create simple animations. The Chart.js website has a lot of documentation with basic information on how to create a simple chart.
Chart.js can be used with plain JavaScript or various module loaders. You don’t have to be a JavaScript expert to use Chart.js to create different types of charts to present your data in great ways. With a little JavaScript and HTML, you can create charts in no time. Chart.js is rendered using the Canvas element which is supported by all browsers.
Import the link of the latest version inside the script tag
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.1/chart.min.js
OR
You can also install Chart.js by using NPM
Copy and paste the command below to download it into your project:
npm install chart.js --save
You can set up your project with CodePen or use a text editor like VSCode.
Create a simple index.html file and load the CDN in the body section. We will also create a script.js file in which we will later add code to create charts using Chart.js.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Chart.js beginners guide</title> <link rel="stylesheet" href="style.css"> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.1/Chart.min.js"></script> <script src="script.js"></script> </body> </html>
Now that we’ve included Chart.js in our project, we can move on to creating a place to render the chart.
Create a canvas tag inside the body tag:
<canvas id="myChart" width="800" height="400"></canvas>
The ID is very important and you can name it whatever you like, but it’s best to use a meaningful name that represents the type of chart you’re rendering.
The body tag now should look like this
<body> <canvas id="myChart" width="800" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.1/Chart.min.js"></script> <script src="script.js"></script> </body>
Now let’s prepare data for the graph which we want to show
Month (x-axis) | Data (y-axis) |
January February March April May June July | 83 51 95 94 61 29 46 |
We are integrating a graph for data which have shown in the figure above
Now create a script.js file, open it and write the code given below
var data= [83, 51, 95, 94, 61,29,46]; var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
As you can see, each Month in the Months variable corresponds to the number of the value data variable. The accuracy of figures depends on this.
Now to create a bar chart write the corresponding code on top of your script.js file
var ctx = document.getElementById("myChart");
This code gets the canvas element from the HTML with the id chart1 and stores it in the variable ctx.
Variables can have any name. ctx is just convection that most programmers like and use it.
Now let’s create the chart. To create a chart, we first need to create an instance of Chart().
To create an instance, we need to call new Chart(), so enter the following code:
var myChart = new Chart(ctx, { type: 'bar', data: {} } )
The new Chart() object accepts the following arguments.
ctx is the variable used to store the canvas element. A
configuration object that allows you to set the chart type, data, and chart options.
The configuration object looks like this:
{ type: 'bar', data: {}, options: {} // optional }
Here are the property descriptions:
Type: ‘Bar’: Allows you to specify the graph to create. In this example, we will create a bar chart. If you want a pie or line chart, you can specify it as type: ‘pie’ or type: ‘line’.
Data: Contains the data (labels, datasets) used to draw the graph.
Options: Contains configuration options to customize the chart. Such as changing the position of the legend, enable/disable responsiveness, controlling styles, etc.
The code hasn’t rendered the chart yet, so in order to render the chart, we need to add some data (see next Save it in the framework and star saved in a data object like
var myChart = new Chart(ctx, { type: 'bar', data: { labels: months, datasets: [{ label: 'Products sold monthly', data: data }] }, });
Your script.js should look like this now
var ctx = document.getElementById("myChart"); var data= [83, 51, 95, 94, 61,29,46]; var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; var myChart = new Chart(ctx, { type: 'bar', data: { labels: months, datasets: [{ label: 'Products sold monthly', data: data }] }, });
Now open your index.html file with Chrome or any other browser and you should now see a bar chart(Same as the first figure).
And now to understand datasets let me show you what happened here
datasets: [{ label: 'Products sold monthly', data: data }]
The data property object has two properties labels and datasets.
Labels take an array (months) and display each element as a label on the x-axis.
Datasets take an array of objects with the following properties:
➡️ label: The label property takes a string. It appears on top of the chart or when the cursor hovers over the bars.
➡️ data: Data takes an array of values(Months) and displays the data on the y-axis(vertically).
Before we can style the bar, there is an issue that needs to be fixed. This is primarily for people who want to test their code and view charts in their browsers.
You may notice that the browser displays the chart in full-screen mode and does not take into account the width and height you previously set for the canvas element.
<canvas id="myChart" width="800" height="400"></canvas>
To fix this, you need to add configuration to your bar chart instance by passing an options object and setting maintainAspectRatio to false.
var myChart = new Chart(ctx, { type: 'bar', data: { labels: months, datasets: [{ label: 'Products sold monthly', data: data, options: { maintainAspectRatio: false } }] }, });
If you try again in the browser, you can see that the height of the bar chart is 400 pixels, but the width is ignored.
To do that responsive should be set to false for full-width control.
var myChart = new Chart(ctx, { type: 'bar', data: { ...... }, options: { maintainAspectRatio: false, responsive: false } })
Now if run your index.html on the browser again you will see that the width is 800px and the height is 400px.
Another way to control the width and height of the chart is with CSS. However, while this option requires additional markup in HTML, it is flexible because the width and height of the chart are controlled and responsive.
To do that remove the complete options object and replace the code inside your body tag with
<div class="chartWrapper"> <canvas id="myChart"></canvas> </div>
And open your style.css and add the following code:
.chartWrapper { max-width: 800px; margin: auto; }
Now if run your index.html on the browser again you will see it has a maximum width of 800px, and it is also responsive.
Now let’s add some styling on our chart.
➡️ backgroundColor – Takes an array of Hexadecimal or RGBA color values(strings) which will be used to color the bars in the chart.
➡️ borderColor – It takes an array of color values strings, the same as the backgroundColor property. It will color the borders of the bars.
➡️ borderWidth – It takes an Integer or a float value and it specifies how wide a border should be.
In order for you to understand how and when to use each property, we will add them one by one.
To color our bars, we will add the backgroundColor property with an array containing RGBA color values:
data: stars, backgroundColor: [ "rgba(255, 99, 132, 0.2)" ]
You can add multiple colors as per your no. of values to give each of them a different color.
To create a bar chart border, pass an array of RGBA color values using the borderColor property. Add it after the backgroundColor property. Same as the background color you can add more than one color for each bar.
Allows the borderColor property to work. We also need to add the borderWidth. Otherwise, the border will not be visible.
borderColor: [ "rgba(255, 99, 132, 1)", ], borderWidth: 1
Now, what if you want to show the same data but with a Line chart is not very hard to do though.
The following are a few things we need to know:
var myChart = new Chart(ctx, { type: "line", data: { labels: months, datasets: [ { label: "Products sold monthly", data: data, backgroundColor: "rgba(255, 99, 132, 0.2)", borderColor: "rgba(255, 99, 132, 1)", borderWidth: 1 } ] } });
In conclusion, Chart.js is a powerful and versatile JavaScript library that allows you to create visually appealing and interactive data visualizations. With its easy-to-use syntax and extensive documentation, Chart.js enables you to plot various types of charts, including bar, line, area, pie, bubble, radar, and scatter charts.
By integrating Chart.js into your web applications, blog posts, or presentations, you can effectively present data in a meaningful and engaging way. The library is open-source and freely available, making it accessible to users of all skill levels.
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork