Data Visualization with Chart.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up coders hope you are doing well today we are using the chart dot Jes library in order to graphically present poll results visualizing data makes it easier for the user understand information there are many data visualization JavaScript libraries chart dot Jes is one of them it is a very popular open source library and for a good reason since it is simple to use yet flexible lightweight reliable free no watermark not even attribution is needed and it allows us to create clean elegant and responsive charts using the html5 canvas element documentation is great as well so overall I think that chart Jes can be a great charting choice I like it so much that I would even paraphrase the famous line slash compliment you are the CSS to my HTML - you are the chat Jes to my data in our example we are hard coding the data we are not getting or posting data to some database this is beyond the scope of this tutorial the main objective today is to show how we can use the chart JS library in order to present data in our case poll results I hope you guys will enjoy this video don't forget to share like subscribe and without further ado let's go [Music] okay starting with an empty project in our Visual Studio code editor let's create the index dot HTML style dot CSS at the main dot J's files in the index of the HTML file I type exclamation marks as m8 abbreviation vs code comes with the m8 plug-in embedded and if I hit tab or enter we get some html5 boilerplate code let's insert the title all results with chart j s and let's link the external files to the document first the stylesheet yeah we are and the javascript file main dot j s notice that instead of placing the script in the body right above the closing body tag i placed it in the head using the defer attribute so that the script will be executed when the page has finished parsing next let's import the chart Jes library into our project using a CDN this is the minified javascript file so let's copy the URL and place the script here before the main dot j s script again using the defer attribute now let's specify content for the body for starters we will simply add an edge one heading with the title and a canvas element for the chart let's just copy and paste this and instead of setting the canvas ID to my chart let's simply set it to chart okay let's open the project in the browser for this purpose I'm using the live server which is a Visual Studio code extension so this is what we've created up to this point we can't see the canvas element however it should be here so if we inspect here it is the canvas element with ID chart and 400 pixels width and height now before actually creating the chart with the help of the chart.js library let's add some basic styling with CSS I will just paste this part since it is general styling not directly related to the main objective of this video so we are setting margin and padding to zero and Bach sizing to Porter box for all elements or the body we set font family to comic sans ms I thought this would make sense since the pole is about favorite superheroes cursive and sans-serif are the fallback font families we also set background color and color for the body and for the h1 heading we set text align to center and some margin we will not style the canvas element eventually however for now let's set its border to 3 pixels solid and blue just in order to be able to see the area it occupies okay so this is the result of our styling and now let's move on to our javascript file in order to create the chart as a starting point let's use the example from documentation from the introduction section in the let's replace bar with Const so we are selecting the element with ID chart this is the canvas element for the chart and called the gate context method over it with 2d as an argument this returns an object that provides methods and properties for drawing on the canvas which we store into this variable city X and we then create a new chart using the chart jes library passing CTX as the first argument and the configuration object as the second argument we will come back to this of course in a bit but first let's save and check the result after changing the name of the chart to Paul chart instead of my chart indeed we get the chart however the chart canvas should have 400 pixels width and height what's happening here well that's because in order to achieve responsiveness for the chart canvas element chat Jes uses its parent container to update the canvas render and display sizes in our example currently the parent container is the body so in order to control sizing while maintaining responsiveness we should use a container element a relatively positioned and dedicated to the chart canvas only responsiveness can then be achieved by setting relative values for the container size and here is an example so let's include our chart canvas within a container element and in our CSS file let's set position for chart container to relative we should do this according to documentation although everything seems to be working fine without it as well and let's set weight to 45 percent of viewport width very nice and in order to Center it horizontally let's also set margin to auto okay now let's inspect and we can see that canvas is square with width and height 864 pixels but why is that where did we specify width to height ratio is this the default behavior for example in addition to setting width for chart container let's also set height to 22.5 viewport width so that width of chart container is twice its height in other words width to height ratio is 2 to 1 let's save and check the result as we can see setting the containers height doesn't have any impact in aspect ratio so chat canvas will respond to the width of its container however aspect ratio is defined over the canvas element itself currently aspect ratio is set to 1 and that's why we get a square chart if for example we set height to 300 then we get an aspect ratio of 4 to 3 or if we set it to 200 then we get an aspect ratio of 4 to 2 or 2 to 1 so if we inspect indeed width is 864 pixels and height 432 aspect ratio 2 to 1 note that by default chart jes set aspect ratio to 2 to 1 so if we don't explicitly specify aspect ratio we expect it to be 2 to 1 let's confirm looks okay and if we inspect again width is 864 and height 432 aspect ratio two to one and by the way I think the default width is 300 and height 150 alternatively we could specify aspect ratio in the chat configuration object here in the options field let's set aspect ratio 2:1 in order to get a square canvas okay just keep in mind that by explicitly specifying aspect ratio here we override the configuration setting a final note regarding sizing according to chat canvas aspect ratio we can set the height for chart container in our example this would do since aspect ratio is 2 to 1 so that it takes up the required for the chat space on the page for example while fetching data so that subsequent content doesn't have to move as soon as the chart is created and we don't want this anymore ok now let's move back to our javascript file and discuss the chart configuration object for starters we observe that it consists of three main fields or first level fields let's say type data and options in the type field we specify the chart type chart Jes currently comes with 8 built-in chart types line bar radar donut and pipe polar area bubble and scatter area charts as well as mixed charts are derived from the main chart types next main field is data here we specify an object with the data related properties or fields I'll be using both terms interchangeably here and by the way this is in general how we work with chart Jas starting from the main field we drill down through nested objects until we get to the property we want to modify you now in the data object we have two main fields labels and data sets the labels are a specifies the x-axis values the length of the array defines the length of visible data for example if we removed the last three values then the last three bars of the chart would also be removed despite the fact that data for these labels still exist in the data array data set is an array of objects each object representing a data set here we only have one data set for which we set the label number of both the data of course which is an array with the corresponding to the labels values in the case of a bar chart these are the y-axis values and we also set background color and border color for each bar and border width now let's comment this out and see how our chart would look if we didn't modify them okay so this is the default styling and now let's uncomment border width and set it to 3 this is in pixels by the way okay and let's uncomment border color nice and finally let's set the same background color for all bars for example let's set it to black so let's uncomment these remove all colors except for the first one which we will set to zero zero zero and let's set opacity 2.75 not exactly what we wanted only the first bar gets the desired background color in order to set all bars to the same background color we shouldn't include it within the array much better for more data set properties you can specify in a bar chart feel free to check documentation in the bar chart section and let's specify one more property for example the hover background color which sets the background color when hovered and let's set it to black alternatively we could use RGB a with opacity 1 very nice and finally we can use the options field in order to specify how the chart behaves for example here starting from the main options field we drill down to scales Y access ticks and set the begin at zero property to true in order to force the y axis to start from zero if for example we comment out the options configuration we can see that Y axis starts from two which is the minimum value in our data and if you are wondering how could we figure this out don't forget that documentation is our friend for example we could find this under axis Cartesian linear tick configuration options and here is a property we are looking for let's see if there is some example that would make our lives easier here it is and all we have to do now is set the begin at zero property to true in here of course when searching for answers Google or some other search engine can be of great help especially for a popular library or framework which has been around for a while such as chart.js there is a very good chance we will quickly get the answers we are looking for okay regarding the legend notice that by clicking on the legend ones related bars are removed by clicking again they are added back now this would make more sense if we had more than one data set however in our example I think it would be better if we removed it so options legend display Falls nice I think now it would be a good time to add and present the poll data so let's do this whole data is an array of objects each object representing an option let's go through the first object and I will paste the rest so we have the option field first option is spider-man and the Volt's field this is the number of votes for spider-man it is 11 now we could leave it here and set the chart related colors in the chart configuration object or store the colors array into a separate variable however I chose to include the corresponding colors here in the color field as a string with the RGB color value for Spidey it is a reddish color so maybe a more exact variable name would be Paul chart data however I think all data is also fine and let's paste the remaining call options after spider-man we have Superman Batman son Goku Hulk Wolverine and other ok let's save and proceed in order to get the labels array we will use the map method over pull data in order to loop through each full option object and extract the option value ending up with an array of options okay and let's do the same for the data array this time we want to extract the vault property value and for background color extracting the color value and let's remove border color as well as Hoeber background color and let's check the result nice now if we wanted to add transparency to background color and perhaps use a fully opaque bottle similar to our initial example I've created this RGB to RGB a function which takes the RGB color string as the first argument and the alpha value for opacity as the second argument and returns the RGB a color string I will not expand on this since this is actually me just playing it is completely irrelevant to the main objective of this video as usual I will include a link to this project in the description in case you want to have a closer look and let's use the function here this should be the first argument they RGB color let's set opacity 2.25 it works but I think it's a bit too transparent so let's increase opacity 2.75 okay now let's also add a title to our chart so in documentation let's try and figure out how we can do this configuration title here are the title properties we can modify in order to show the title we should set the display property to true we should also set text for the title some other properties are font size font family font color padding etc and let's see if there is some example here it is so in the options object we specify the title configuration let's copy this part and paste it here display property for the title is of course set to true text will be favorite superheroes and let's also set font color to dark gray font size to 20 pixels same as for padding okay let's save and check the result nice and finally I would like to change the phone family for all text in the chart so that it matches the phone family of the body so let's go to documentation font there are four special global settings that can change all of the fonts on the chart sounds promising these options are in charge to default dot global the global font settings only apply when more specific options are not included in the configuration object great and here is an example where the global default font color is set we are interested in setting the default font family here it is and this is the default value so I suppose we should include font families within quote okay let's do this let's place it here and let's check the result marvelous now before adding the poll in order to show how we can dynamically update the chart in our example as soon as a user submits an answer to the poll let's quickly go through a few alternative chart types that make sense given our data set just in order to show how simple it is to experiment with different charts using chart chairs or starters let's set type to horizontal bar which is a variation of the bar chart it is actually a vertical bar chart and this is the result as simple as that again we have the same issue this time with x-axis starting from 3 which is the minimum value in our data and again all we have to do in order to fix this is to set the begin at 0 property to true this time for x axis okay and of course if we wanted we could sort and present data in ascending or descending order now let's set this back to Y and change chart type to line okay and I would prefer to remove feeling of the area below the line I would to also prepare to have straight lines instead of a curved line and let's also increase the size for each point we can do this here in that data sets configuration I will paste in order to save time so we are setting the field property to false in order to remove feeling of the area under the line line tension to zero in order to get straight lines I think default is 0.40 in the radius to ten default is three and point hover reduced to twelve default is for in order to increase point size so let's save and check the result very nice there are of course many many things you could change and customize the chart according to your needs we are just scratching the surface here now let's remove this line related configuration and change the chart type to pie looks good nice out-of-the-box animation as well animations are of course also configurable first thing I would like to fix is to remove these gridlines in y axes and all we have to do is to remove this part the scales configuration in the options object I will just comment it out since we will eventually need it for our bar chart much better now in this type of chart it would also make sense to display the legend allowing for the labels to be displayed nice and let's reposition the legend for example positioning it to the right and let's increase padding for labels to 20 pixels default I think is 10 okay now if for example we cancel the option other by clicking on it then its percentage is redistributed two remaining options for example Superman and Wolverine have 8 volts each so if only these two options are left then each gets 50% of the pie and the let's move on to donut chart which is basically a pie chart with a hole in the middle spelling the word donut is probably the hardest part here voila nothing really to add here so let's move on to the next chart type the last we are presenting today color area here it is color area charts are similar to pie charts but each segment has the same angle and what differs is the radius of the segment depending on the value for example if we only had spider-man Hulk and Wolverine then we can see that each segment has the same angle in this case 120 degrees and what differs is the radius depending on the value in other words with polar area we are comparing data through differences in length while with pie chart through differences in angle okay let's not expand any further there are also other chart types such as radar or bubble which are great for visualizing certain data sets feel free to experiment now let's remove changes and continue with our main example so up to this point we've created the chart according to current data but what if we wanted to update the chart after it has been created as soon as data changes chart.js makes it quite simple to update the chart animating to the new data values in order to demonstrate this we will create a poll allowing the user to vote for an option and update the chart as soon as the new vote is submitted so let's move back to our HTML file and add the mark-up for the poll not in here this is the chart container I will paste this part so called consists of three main parts all heading for the title whole body for the list of options and all footer for the vote button to submit the selected option we are using radio buttons for the options all options share the same name all options and of course the value attribute defines the unique value associated with each radio button this is the value we are going to extract upon submission and it should be the same as the option field value of all data objects since by matching these values after submitting we will know which option was selected and proceed to updating the world field value for that option okay and although we are not actually sending data anywhere let's include the pole within a forum just in order to be semantically correct form will have the ideal pole for we don't need the action attribute and now this button becomes the form submit button so let's set its type attribute to submit back to browser here is the call and let's add some styling so let's move back to our CSS file I will paste styling for the pole in order to accelerate and focus on the main task which is to update the chart upon pole submission again you can find a link to this project in the description so we are styling the pole container element and pole heading and pole body with its lists and list items and labels and the pole footer with its button we are also adding some basic responsiveness just notice regarding chart container that while screen size decreases we increase the width percentage and correspondingly the height maintaining the two to one ratio okay let's save and proceed this is the pole after styling and our final goal is to update the chart after submitting an option for example it will choose Superman and submit clicking the world button we want the corresponding bar to get from 8 to 9 currently of course form is submitted to the current page since we didn't set a value for the action attribute and form data is appended into the URL as a name value pair not exactly what we want and that's why we will prevent the default behavior from happening and manually handle pole form submission with JavaScript so let's move on to our javascript file and for starters let's get the pole form element and store it into a variable for easier access for this purpose we can use the query selector method in here goes the CSS selector next we will add an event listener to the pole form element for the submit event and whenever poor form is submitted we want to call the poor form submit function we will implement this function right now first thing we want to do is to prevent the default action from happening in this case form submission and then we want to access the selected option or in other words the selected input radio button and store it into a variable starting from poor form since we are looking for a pole form descendant element again we are using a query selector method and select all these input with the name attribute equal to all options and with the pseudo-class checked present in order to get the selected option now we only want to proceed if indeed some option was selected and in this case we want to get the actual value of the selected radio button input and store it into a variable and given the selected option we can find the corresponding object in all data and update it votes field so let's do this finally in order to update the chart we can set the data array in data sets to the updated data and call the update method over the chart so this is in general how we can update a chart with chart Jas first we change the data array and then we call the update method over the chart now regarding the data array we could alternatively get the index of selected option and simply change the specific data point given of course that poll data and chart data maintain the same order or in the case of a new data point we could use the push method the same of course stands for the labels array the background color array etc okay let's save and check the result let's vote for Superman who currently has eight votes watch the blue bar I'm submitting right now indeed the corresponding bar gets from eight to nine with a smooth animation thank you charge a yes and it will check the console no errors in the console let's also vote for son Goku watch the orange bar nice and for Hulk green bar again and again and again obviously we have unlimited number of votes and it will fresh the page all changes are lost since we are not actually sending and storing data to some database I suppose we could reset poll form after submission just for presentational purposes and all we have to do is to call the reset method over the pole or or alternatively since we only have a radio button group we could set the checked property of the selected option to false okay guys we are done I hope by now you feel confident enough to start using charges and incorporate it into your project in order to visualize data if of course it fits your needs this goes of course just an overview and by no means an exhaustive walkthrough of chart.js documentation and capabilities if you enjoyed this video and got some value out of it please hit the like button and share it with anyone who might be interested don't forget to subscribe if you want more I would love to hear your thoughts in the comments section below until next time keep coding keep improving and a joy the journey take care bye
Info
Channel: Coding Journey
Views: 15,922
Rating: undefined out of 5
Keywords: chart.js, chartjs, chart js, Data Visualization with Chart.js, chart.js tutorial, chart js tutorial, data visualization javascript, poll results with chart.js, visualize data with chart.js, chartjs tutorial, how to use chart.js, data visualization chart js, intro to chart.js, using chart.js, chart.js visualization, graphing with chart.js, javascript charting library, how-to, html, css, javascript, tutorial, web tutorials, web development, front-end tutorial, ux, coding, coding journey
Id: DSlUGncFxa4
Channel Id: undefined
Length: 41min 7sec (2467 seconds)
Published: Fri Feb 14 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.