Chart.js | How to Add Charts in HTML Websites 🔥 (Pie Charts, Line Charts, Bar Charts & More)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
chart.js is one of the most popular javascript libraries when it comes to adding charts to an HTML website. The integration of the library is pretty straightforward and allows you to show graphics such as pie charts, line charts or bar charts in no time on your HTML website. In this tutorial I will gonna show you how you can add chart.js to your next big project and especially how to handle for instance data streams that needs to be passed to this library or how you can customize charts such that they perfectly adapt to your personal style and lastly also how to re-render charts based on upcoming data updates. At the end of the tutorial we will discuss one more very specific very exotic chart type and if you don't want to miss that one make sure that you watch the video until the end and now i would say let's get started. To make this tutorial more fun we will not start from scratch but rather embed our charts into a real live project. To do so I have already prepared a mock-up that emulates the dashboard of a personal financing app which is actually missing some nice graphics for its users and guess what that's going to be our task for today. The dashboard holds up four empty card elements where we will embed a mixed chart of a bar and line chart in the upper left corner a pie chart in the upper right corner a radar chart in the bottom left corner and a bubbles chart in the bottom right corner. To follow along with this tutorial you don't need to fully understand the code basis of the mock-up dashboard, it's only needed to demonstrate chart.js use cases in a more realistic scenario. For those of you who would yet like to explore the whole project you can find a link to the source code in the video description and at the end of the video. All right before we can embed our first chart type into the app's dashboard let's start with some general setup to import chart.js into our project. First of all as for any external library we have to include chart.js script tag into our HTML header. I will add a link to the chart.js repository in the video description if you want to check out the latest version of the library. As of today we are going to use its current version 2.9. Apart from chart.js we will also need a library called moment.js moment.js allows us to properly deal with timescales on charts x and y-axis. More on that topic later in the tutorial. The canvas elements that will allow us to attach our charts to the DOM are going to be stored as child elements to chart canvas. The charts themselves are then added via DOM manipulations through javascript such that the canvas elements only need unique IDs to be identified separately later on. As we will discuss in total four different chart types let's already prepare the canvas container for all of them right now. OK, cool so now everything that is left to do in the HTML document is to include our javascript source code and we are ready to go. Notice that we are adding two different script tags to our document. utility.js contains sample data and helper functions to compute data streams needed for the visualization in chart.js script.js on the other hand is responsible to actually add and customize the charts to our applications and hence we'll be in focus of this tutorial. Although we do not need to fully understand the underlying mechanics of computing the data streams let me show you one aspect that is set up in the utility.js for a better understanding of the use case that we are discussing. We can see in the first lines of code some plain data sets which were predefined for this project. Most important is the array of objects called FinancialData. The array FinancialData contains a sample of 96 dummy transactions that could have been purchased more or less in this way by our test user John Doe. Each transaction holds information about the value date, the product and its associated product category, the paid or received amount as well as the payment method. Together with a balance at the beginning of the reporting period and an object of benchmarking data to compare expenses by category these are the raw data sets used to draw our charts. Alright that's more than we need to know about the source code of utility.js. Anyone who is interested in further details will find the entire source code at eversparked.com. Link in the video description. OK, so now let's dive into the main source code. In just a few minutes we will understand that the data as defined in utility.js is indeed useless for the visualization of our chart. Every chart type needs its own representation of data and it's important to keep in mind that chart.js does not provide any functionality for data manipulation. So what does it mean? That's pretty simple! chart.js is only visualizing the data in a nice and appealing fashion but it's not manipulating the data. This task is up to you as a developer to take care of appropriate pre-processing actions. OK, so let's start with our first use case. The chart on the first dashboard card shall show liquidity planning for John Doe. Any of his cash flows during specific period in time shall be represented through a bar chart whereas income and expenses shall be treated as independent data sets of cash flows. To do so we attach a new element to the HTML canvas with ID LiquidityPlanning. This element is then passed towards the creation of a new chart element together with the definition of the chart type; in this case a bar chart. Further parameters are the clean data streams which shall be visualized and any customization option for which you would like to deviate from the default settings. The necessary data for the chart is already pre-processed through utility.js and is stored in costGroupedByDate and incomeGroupedByDate. The content of these two arrays includes data objects that holds x keys for the time axis and y keys for the cash flows spent or received on that day. DataLP is then easily defined as an array of objects where for the time being we only provide one entry in that array with a data specific background color, in this case red for outgoing cash flows and the data stream CostGroupedByDate that shall be rendered. Now let's define optionsLP as an empty object to avoid runtime errors and test if we can already see our first chart. Nice! We added a bar chart to the canvas but something is still not working as expected. The x-axis is defined in the data set as a time object of the moment.js library we added in the beginning in our HTML document. In order for chart.js to interpret this format correctly we have to explicitly state its usage in the optionsLP variable. The access settings are defined within the object's key scales and can be differently customized for x and y. So let's define the x-axis as of type time. Awesome! All data points are rendered correctly and we have created our first chart. Now before we proceed we should do some further fine tuning for this bar chart. Let's remove the legend of the data set from the chart as the color coding already reveals the nature of the data set. We need a title let's add liquidity planning with a font size of 24 pixels and font family Roboto, sans-serif. Great! The grid layout does not really fit well to a bar chart so let's remove at least the vertical grid lines. Last but not least the amount of the cash flow on the y-axis is represented as a number type but we rather like to show a currency amount. Using the user callback function allows us to do some custom changes to the ticks label of the y-axis. Great! Our first chart is now styled as we want it to be. So now let's figure out how to add the data set of incoming cash flows to the chart. The incoming cash flows grouped by date are stored in the variable incomeGroupedByDate and its data structure is exactly the same as for variable costGroupedByDate. To add a new data set to the bar chart we only need to extend the data set array with a new entry. Let's choose green for the background color and add incomeGroupedByDate as data set and here we go with just a few lines of code we extended our bar chart with one additional data stream. OK, all good so far, john doe has a pretty nice overview of his incoming and outgoing cash flows in the app's dashboard, but actually who cares about daily cash flows without knowing how much money he actually has in the bank? Right, we need to add another data set which represents John's bank balance at every day of the period to check that he's not running off out of cash. To do so we need two things. Firstly we need a balance at the very beginning of the reporting period which we will set to some fixed value. Secondly we need to calculate a new end of day balance for each reporting day by adding up incoming and outgoing cash flows to the balance of the previous day. You can check the calculation in utility.js but for now we are going to use the final result stored in the variable totalsAccGroupedByDate. Again this variable has the exact same data structure as the other data variables so we just need to add a new entry to the dataset array in order to display this data set. Since the balance data set represents another kind of information as the two cash flow data sets, let's use a different chart representation for the account balance and mix the bar charts with a line chart type. chart.js let's you define the chart type globally during the initialization of the new chart object. However, this can be overruled at the stage of the data set which we will do for the balanced data stream by setting the type to line. Now we rearrange some customization options such as line color and the line width and remove the default filling pattern and here we go, a nice line type chart on top of our two bar charts. Great! That was pretty straightforward and lucky you John Doe your bank account seems to stay above zero. Now let's add another chart to our dashboard. Imagine the following situation. John has recognized on the first chart that he's spending a lot of money every day, but he doesn't really know for which products. We can give John some insights by visualizing his relative spending splitted by product category through a pie chart. To do so we add a new chart object to the second HTML canvas with the ID ExpensesByCategory. This time the chart type is going to be a pie chart and again the only thing we have to provide is the data stream and our configuration options. Starting with a letter let's define a suitable title for our chart and this time include a legend for the product categories to be shown. The legend is going to be centered on the right hand side to the pie chart and we are done with our minimal configuration setup. The data for the grouped expenses is stored in the variable costGroupedBycategory. This time as chart.js expects a different data structure for pie charts as for bar and line charts, let's take a quick look at its underlying structure. costGroupedByCategory is an object that holds the two keys category and amount. The value of both keys are arrays with the amount spent and in the latter case the individual product category. Keep in mind that for pie charts the order within these two separate arrays is important which means the first entry of the category array has to match the first entry of the amount array and so forth. costGroupedByCategory.amount can be added to the data set together with a predefined array of background colors. Border width and border colors can be set too. The associated labels to the data sets are configured separately within the key labels. Let's put it to costGroupedByCategory.category. Awesome! In now time we have our second chart up and running. One really nice feature of chart.js that I like is its ability to easily interact with the chart. If you would like to remove one of the data sets just click on one of the chart labels and chart.js dynamically removes the data set for you and adjust the pie chart through a smooth animation. Clicking on the removed category will let it appear again. Great, but how does chart.js work with updates of data for example if the user wants to change the view from expenses to income per product category? To demonstrate this let's do some refactoring of our code. Setting the data of the pie chart is encapsulated into the function setDataEC() that accepts the data stream to be shown by chart.js as a functional parameter. Let's initialize dataEC with the expense stream costGroupedByCategory as before. So to see the magic we define a second function called updateStreamEC() that is responsible to update the data in the chart object. Calling pie chart.update() triggers chart.js to re-render the pie chart and we only have to add some logic that allows us to switch between incoming and outgoing cash flow streams. Now let's switch to our HTML template and add a selection object with the two options expense and income. Connect our previously defined function updateStreamEC() to be triggered on a change event on the selection and a drop down list on the dashboard card becomes available that allows the user to switch between both cash flow streams. That's pretty cool and the described pattern allows us to easily update charts when data streams have changed. In our case the data change was triggered by user interaction but also other events such as data updates from a data API could be handled a similar fashion through for example event emitters. Before moving on to our next chart type, let's take a look at one more subtle configuration option for the pie chart. Pie charts and doughnut charts are more or less the same objects for chart.js and you can switch between boths when interchanging chart types during initialization. So let's do this and change from pie to doughnut. You can see the chart on the canvas has changed into a doughnut representation. The same can be achieved with a configuration option cutoutPercentage which takes values between 0 and 100 and allows you to continuously define the relative percentage of the inner circle of the doughnut. This means the pie chart is equal to a configuration of cutoutPercentage equals to 0 and the doughnut chart is equal to a configuration of cutoutPercentage equals to 50. Of course any other value between 0 and 100 is also allowed. The user story of the third chart goes as follows. Thankfully John Doe can now analyze his expenses based on product categories, however John has also identified that he could save some money based on optimization strategies for the payment method that he has chosen for his expenses. Hence he would like to analyze through which payment method he is spending the most money. The requirement could also be represented by a pie chart but let's go for the radar chart this time. To do so let's add a new chart object to the HTML canvas with the ID ExpenseByPaymentMethod. The type will be radar and we only need to define the data and configuration options. The data is stored in the variable costGroupedByPaymentMethod and its structure is exactly the same as for the pie chart. We do have an array of amounts and array of categories whereas this time categories are not product categories but rather payment methods. The configuration option includes a title as before the legend is not needed as we are showing only one data set so let's set it here to false. The default setting for the background color of the grid lines do not have sufficient contrast to the background color of the dashboard cards so let's change it to white. The distance of the grid lines can be changed by the step size. We set min and max values to 0 and 40 and increase the step size from 5 to 10. Labels need to be slightly larger so let's change it to 16 pixel and we are done. Awesome, how fast chart.js allows us to add new charts and chart types to our project in no time. Therefore let's rush over to our last chart for today. The bubble chart is one of my favorite chart types because it allows you to visualize data in three instead of just two dimension as it is usually the case for most other chart types. The bubble chart is rather underestimated in its ability to present data in a clean way. So I decided to take it into a today's project as a rather exotic chart type. OK, but before we dig into the details let's recap what is our use case here. John already knows how much money he is actually spending per product category as shown in the pie chart. This information will be the first dimension of our bubbles chart. However in order to find product categories he is spending too much money for John would like to understand how much others are spending per category. This benchmarking data is defined as our second dimension. Lastly it is important to understand if this category makes up a substantial part of all his expenses. This relative weight of each category compared to the total expense is our third dimension. So last time for today let's add a new chart object to the HTML canvas of type bubble with the ID ExpenseByCategoryBenchmark. As mentioned before we now have to deal with three-dimensional data. Therefore the data structure has to be different as for the previous chart types. So let's take a closer look. The data is stored in the array costGroupedByCategoryBenchmark which contains data objects for the background color the labels and the data stream itself. The data variable is an array of objects with the coordinates x and y and r. x and y will determine the position of the bubble in the chart and r provides us with the radius of the bubble to be drawn, measured in pixels. The data array contains only one entry such that each bubble has its own label and color. Several entries in the data array would automatically be customized in the same fashion which is not the way we would like to style our chart. Great, that implementation went smooth. Now let's do some fine tuning of the charts configuration option. As always we need a suitable title for the chart and hence the legend needs to be positioned to the right. We force the x axis to begin at zero and both x and y axis shall be shown as a currency amount. We can use the same trick as for the line chart by adding the user callback function. As this time it is not entirely clear which axis shows the benchmark and which shows John's data we need to add data labels to the axis. Great, that looks already pretty cool. The bubble chart gives John an indication for which product category he is spending more respectively less than others. For any bubble that is below the diagonal John is performing better than average and for any bubble above the diagonal he is performing worse than average. Let's make this more explicit and add a borderline between low and high performance regions into the chart. For this to work we add another data set of chart type line to the bubbles data set. For a straight line to be drawn we only need two data points with the first point at x equals zero and y equals zero and the second data point in our use case x equals -2500 and y equals -2500. Then add some styling instructions and we are done. Notice that we added the line data set to the beginning instead of pushing it to the end of the array costGroupedByCategoryBenchmark. Doing so, chart.js s draws the border on top of the bubbles instead of vice versa Awesome! The chart is drawn as expected. Now to optimize John's financial data effectively we can give him the advice to investigate the largest bubble below the performance border. OK, so that's it for today's tutorial on chart.js and its most interesting chart types. I hope you have learned something new and if so you could really help us out if you hit the like button and subscribe to our channel. If you have your own ideas where you could use chart.js in your next big project or you have already seen a pretty cool project on the web that uses chart.js share your knowledge with us in the comments below. And as always if you would like to code along live as the tutorial progresses, do your own experiments directly in the code and download the full source code of this project, watch this and many more tutorials in our browser-based live coding editor at eversparked.com! Link in the video description. Thanks for watching, bye for now and see you next time!
Info
Channel: eversparked
Views: 6,092
Rating: undefined out of 5
Keywords: How to add charts in html websites, how to add charts in html, add charts to website, how to add charts in html page, how to add chart in website, chart.js bar chart, chart.js line chart, chart.js bar chart tutorial, html line chart, chart.js line chart tutorial, html bar chart, using chart.js in html, chart js pie chart, chart js bar chart, chart.js dashboard, line chart html, pie chart html, bar chart html, eversparked, 08jzs5q, pie charts line charts bar charts, chart.js
Id: 4beAfc2OdFQ
Channel Id: undefined
Length: 20min 8sec (1208 seconds)
Published: Tue Oct 06 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.