When you're starting out as a beginner JavaScript developer, I think it is important to pursue interesting projects. That way you can make sure you have fun as you learn, and you'll likely find an area of specialization that you enjoy. Show As they say, "If you love what you do, you'll never work a day in your life". Source: giphy.comIn this article, I will introduce you to front-end data visualization, which is my personal passion. Perhaps it will become your passion as well! The most rewarding moments for me as a developer are when I can see or experience the results of what I've made. It’s highly satisfying to create a chart that reveals interesting insights about its data, or an interactive experience that helps explore details of a unique data set. The more significant the result, the more rewarding it feels. However, I have realized that the amount of work you put into a project does not necessarily correlate with the sense of accomplishment – sometimes it feels great even when it was relatively easy. Over time, you will find tools that will help make you more efficient, and sometimes you will move mountains with little effort. There are many chart libraries and tools available in the data visualization field. With the right tools, you will create new charts with little effort, regardless of the type of chart you need. Personally, I think that datavis yields a great reward on your investment of time and effort. In this tutorial you will use a number of tools to get data over the internet, process it, and draw a beautiful chart that can be viewed in any modern browser. You can click the links below to download example code for each step individually, view them all on GitHub, or download all steps at once here: all-steps.zip. The ResultBy the end of this tutorial you will create this interactive data-driven chart. You will learn how to get data over the internet, process it, and make a chart with that data. You will also be able to make your own charts from scratch. Interactive JavaScript line chartAfter processing the data and charting it, you will also learn how to make adjustments to the chart including modifying the default legend, enabling x axis crosshairs with tooltips, and applying text annotations to add context and other information to the chart. To get started, use an internet browser like the one you're probably using to read this article. I recommend Chrome as it offers a great experience and built in tools for developers. Next you will need a text editor. Something as simple as notepad will work. But, I suggest using a more advanced code editor such as VS Code, as this is an environment you will spend a lot of time with. It will give you a more convenient and pleasant coding experience, and it makes writing HTML5, CSS, and JavaScript easier on the eyes. Most important, if you forget a quote or comma somewhere, a code editor can help you find the error. This article can help you choose the best JavaScript code editor for web development. You will use the JSCharting chart library to automatically draw and add interactive functionality for this chart. No other JavaScript libraries such as jQuery, or front-end platforms including React and Angular (commonly used for website projects) will be required. Why JSCharting?JSCharting is a JavaScript charting library that can draw many different types of charts using SVG. It is easy to use and get started with, so it's a good fit for this tutorial. The API (Application Programming Interface, aka the options and settings necessary to create charts) makes difficult things simpler and it is a good option when experimenting with data visualizations. You can use JSCharting for free for personal and commercial use with the included branding. You can create responsive charts with JSCharting through a couple simple steps:
That's it. JSC will draw a professional looking chart populating this div tag with SVG element visuals. The chart will be responsive and interactive without any extra effort. The DataYou will use a data file provided by the NCHS (National Center for Health Statistics) listing historical life expectancy of males and females in the US. You can find it here: https://data.cdc.gov/resource/w9j2-ggv5.csv. This CSV file contains data that categorizes the life expectancies by year, race, and sex. You will use some of this data to draw a simple male/female trend line over the last 100 years. CSV (Comma Separated Values) is a great format for transmitting data over the internet. It is compact, human readable and you can open it directly excel, which is also nice. So without further ado, let's get started. Source: giphy.comStep 1 - Add a blank chartThe first zip file contains a blank starting point you can fill in as we go. If you get lost or confused, or want to skip ahead, the zip file at the end or throughout each section will bring you up to speed. If you wish to download all the files at once, see all-steps.zipinstead. step1-a.zipThis zip file contains the following files.
The The first step is to add some scripts to the HTML web page file. Normally people suggest adding This technique loads all the HTML into the DOM before executing any JavaScript. The chart needs the HTML loaded before it can draw in it. The DOM (Document Object Model) is a representation of your HTML code in the browser memory. Once HTML is loaded into the DOM the browser can display it and JavaScript can interact with it. Start by adding the JSCharting library to the HTML file. Open the
This library URL points to a CDN (Content Delivery Network). It hosts the chart code and makes it convenient to quickly add the library to any HTML page for prototyping charts and experimenting. You can also download and use the library locally or use the npm package in your project, but the CDN does not require any extra steps. Next, using the same technique, add another script tag referencing your blank JavaScript
file. Add this script after the
Great. We are almost ready to draw a blank chart. The last thing you need to do is add a Add this HTML code inside the
The div must have an id so you can tell the chart which div to draw in. In this case the id is You may notice the style attribute of the You're all set with the HTML file. Open the
Open the Not much to see yet, but you might notice a small JSC logo on this page. That indicates a chart is wired up and drawing. JSCharting logo shows the chart is workingstep1-b.zip Step 2 - Play with the chart a little bitOk, as a test, let's add a couple values for the chart to visualize to see how it works. Going back to the
Now refresh (F5) the browser window
where the Nice! You just made your first chart using JavaScript. Source: giphy.comYou made a bar chart by setting the chart type option to All chart data is made up of series and points. A series is simply a group of data points. Charts can contain one or more data series. Data points consist of values that map to the x and y axes. Points can also include many other descriptive variables and values. The example above contains only one series. Now let's look at the options for a chart with two series. Replace the content of the JavaScript file with this code.
Refreshing the browser window will show this chart. Horizontal column chart with two seriesThe chart options look similar. Still a bar chart, but this time there is an extra object in the series array. We also added name properties for each series so the chart can identify them in the legend. If you are interested in making different charts like radar charts, area charts, pie charts, gantt charts, or even calendar heatmap charts, take a look at the JSCharting examples gallery and the source code (chart options) used to create those charts. You can quickly learn how to use other chart features by copying the available examples. step2.zip Step 3 - Prepare the dataSource: giphy.comThe CSV data format is exactly that – Comma Separated Values. The file contains rows (lines) and each row represents a record or entry. Normally the first row of values contains the names of each comma separated value (column). Subsequent rows contain the values themselves.
CSV is human readable, but there are variations of this format. Sometimes if values contain commas (e.g. mailing addresses) the format doesn't work as-is so each value is also wrapped in quotes. That way the commas inside quotes are ignored and the format can still work by using only the commas outside of quotes to separate the values.
Values can also be separated using a different character like tabs in place of commas. But let's not get bogged down in minutia. JSCharting provides a number of tools that help with this process and we will use one of them to skip worrying about the CSV file format and convert it to JSON (JavaScript Object Notation). The result will be an array of objects. Each object represents a row with named properties. The first row in the CSV file is used to define the names of those properties. This is the url of the data we are interested in: https://data.cdc.gov/resource/w9j2-ggv5.csv. You can click to download and open it in excel. CSV file opened in ExcelHowever, you will download and access this CSV data in real-time using JavaScript code. The code below may be slightly confusing at first, but it's short and you can reuse it to get any CSV, text, or JSON files over the internet programmatically. It is similar to the older AJAX technology but much simpler to use. Once again, replace the content of the
Why so complicated? It is because when you request a file, it does not immediately become available. There is a delay and
you have to wait for the file to arrive. So first you request the file from another website using
Then the code inside the
The next
In the
In this case, the error is sent to the console. In the
? Note: The native Drag the Console window outputYou can also paste or write code into this console window to execute it. Try pasting the entire code snippet above into the console window (next to the > character) and press enter. You will notice you get the same result in the console window output. This can be useful for testing a line of code and experimenting. step3-a.zip At this point you have retrieved the text of the CSV file over the internet and sent it to the console to prove that it works. Now we can start to work with it. Let's take a look at this data file to get an idea of what's inside: https://data.cdc.gov/resource/w9j2-ggv5.csv I used excel to sort the rows by the year column to analyze the rows of data for a single year. The CSV data sorted by year.Each year contains 9 rows with data based on race and sex. We are only interested in the highlighted male and female values of all races for each year. You will create two series based on the highlighted rows. A series for female and one for male values. Now that you have an idea of what needs to happen, let's get started. First, let's use the Update the
Refresh the browser to see the updated console output. The console shows an array of 1062 records. And this is one of these records:
? Note: The console can display arrays, and objects for inspection and you can expand and collapse sections in the console to explore details. The property name Add this line at the top of the
You can process this data using simple vanilla JavaScript. The end result we want is two series with data points that include a year and life expectancy for each point. Update the
It defines arrays for male and female data points. Then it calls the array Refresh the browser and inspect the console output. Each row object the callback function encounteredLet's add some logic to filter the data we want and log the result in the console window. Replace the
Inside the callback function you decide whether the row is of interest and use it or if not then discard it.
The logic checks to see if the At the end, you used After refreshing the browser, the console shows the result which is two arrays, each with 118 data points spanning the years 1900 to 2017. The male and female point arraysLastly, instead of passing the result to the console, wrap these data points within an array of two series that the chart can use directly and return them. Add this code at the end of the
If the returned value was sent to the console, it would produce this result. As you can see, the logic for filtering rows is fairly simple and you can adjust it to get other details from this data set. To learn more about handling CSV files using JSCharting utilities, see this tutorial. When you are ready for more advanced data handling, the JSC.nest() utility can be used to create series and points from JSON data with with very little code. step3-b.zip Step 4 - Putting it all togetherThe data handling section was the most difficult step, but that alone will enable you to manipulate and extract data of interest from any CSV file. This is where it all comes together and where you will feel a sense of accomplishment. Start by adding a
In the
step4-a.zip Now, refresh the browser. You should see this chart that uses the CSV data you processed in the previous section. Sweet! ? Whoa, what happened in 1918? Life expectancy dropped significantly there. According to Wikipedia there was a flu pandemic involving H1N1 virus that wiped out a portion of the world population. This unfortunate event shows how visualizing data provides insights you would not normally get from just looking at the numbers. You created a chart using the default line series type and it looks good, but you can make a few adjustments and tweaks to further improve it. First, add a title at the top to explain what the viewer is
looking at and an annotation at the bottom of the chart to credit the data source. Update the
When you refresh the browser you can see the updated chart. Line chart with title and annotation for attributionYou added an annotation with label text, and a position setting. We can use another annotation for the title as well, but it was easier to use the title label in this example. It is easy to control the annotation position using values such as The legend shows the sum of point values for each series, but the sum is not important for this data set. You can reduce the legend columns to only show the icon and series name by using this setting:
But you don't really need to use a legend at all. It will be cleaner to simply label the lines themselves. You can disable the legend, and tell the chart to write the series name on the last point of each line series with these chart options: Line chart using point labels instead of a legendThe Finally, let’s enable the x axis crosshair combined tooltip to show the male and female life expectancy for any given year. On mobile devices, you can tap the chart to see the crosshair tooltip. When using a PC, tooltips display when hovering over the chart with your mouse pointer.
You may be wondering, what's with all those underscores in property names? This is not the actual property name. It's a shorthand way to write:
You may find it more convenient to specify a setting with underscores and JSCharting will understand what you mean. The default tooltip text is clear, but let's customize it slightly to make it our own. Default combined tooltipSince the crosshair tooltip shows information about each point
it crosses, the tooltip text is defined within the point options. The Customized combined tooltipFor more information about this feature, check out the crosshair and combined tooltip tutorial. When you apply all these options, your code will look similar to the following snippet. Replace the entire
Refresh the browser window once more. Line chart with crosshairs and customized combined tooltipsYou did it! Source: giphy.comFirst you fetched CSV data using native JavaScript. You then converted it into JSON format and filtered the data into two series. With those series you created a beautiful interactive line chart using JSCharting and configured it to look professional. You can customize and adjusted the charts further to meet your specific needs. Visit the JSCharting tutorials section to learn more about a specific topic, or find charts similar to what you want to make in the examples gallery and copy them to continue your data visualization journey. If you run into problems working with JSCharting, feel free to contact the support team. They will be happy to guide you or help resolve any issues you may encounter. step4-b.zip Bonus ChallengeWe did not use all the data available in in that CSV file. Let's experiment with it for fun and practice. Create this chart using what you have learned. Challenge: Replicate this chart on your ownThis zip file contains the answer: step5-bonus.zip Can you think of other charts you can make with this data? Keep experimenting and enjoy every minute of it! Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started How can I make a chart in HTML?There are 4 basic steps you should take to create a simple bar chart for your application or website: Create an HTML page. Reference all necessary files.. Create an HTML page. ... . Reference all necessary files. ... . Put together the data. ... . Write the code for the chart.. Does HTML have graphs?HTML Canvas Can Draw Graphics
Canvas has great features for graphical data presentation with an imagery of graphs and charts.
How do I make a line graph in html5?Once the labels and lines are rendered, CanvasChart handles rendering the data points.. LineChart.prototype.drawLine = function (data, color, width). var context = this.context;. context.save();. this.transformContext();. context.lineWidth = width;. context.strokeStyle = color;. context.fillStyle = color;. |