Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 15, 2022 11:14 am GMT

How to Create a Line Chart in JavaScript

Data visualization is a vast field with so many different types of charts to learn and create. But there are several basic, evergreen graphs that every data designer and web developer dealing with analytics should know how to build. One of them is a Line Chart (or Line Graph). Its primarily designed to represent data over time.

You can follow along with this tutorial to learn how to quickly create beautiful interactive line (and step-line) charts using JavaScript. Well look at some cool examples and build them step by step, which will make the process both clear and entertaining.

For your convenience, you can find all of them on CodePen [and on AnyChart Playground] so you could play with the line charting code further without limits.

Our Dataset

The last two decades have been nothing short of spectacular in the world of tennis. The Big Three Roger Federer, Rafael Nadal, and Novak Djokovic have won an astonishing combined 63 (of the past 78) Grand Slam tournaments. These are the most prestigious championships.

I decided to plot their outstanding rivalry. So, the JS line graphs in this tutorial will visualize the Big Threes Grand Slam title race. And the first serve is already coming!

How to Build Line Charts in 4 Steps

Generally speaking, the whole process of creating any chart in JavaScript is broken down into four steps, and a line chart is no exception:

  1. Make an HTML page with a container.
  2. Include JavaScript files.
  3. Add your data.
  4. Code a visualization.

Lets go through each of these steps now.

1. Make an HTML page with a container

To start with, you need a place where you want your chart to appear.

If you dont have one yet, create a basic web page. Then create a container for the line chart add an HTML block-level element and give it a unique ID for further reference.

Heres what such a page might look like:

<html>  <head>    <title>Line Chart JS</title>    <style type="text/css">            html, body, #container {         width: 100%; height: 100%; margin: 0; padding: 0;       }     </style>  </head>  <body>    <div id="container"></div>  </body></html>

The width and height parameters of the element are set as 100%. As a result, the line chart will render all over the web page. Of course you can set the style settings to your own liking and needs.

2. Include JavaScript files

Next, include all JavaScript files, which well use to create the line chart, in the

section.

There are a whole lot of different JavaScript charting libraries which let you visualize data in a fast and simple way. Many of them support line charts, and you can choose one or another depending on your project requirements.

For illustration purposes, in this tutorial, I am using AnyChart JS Charts. Its flexible, comes with extensive charting docs and API references, and you can use it for free (unless you are building something for a business.)

For the line chart, I add the Base module from the CDN. (Of course, you can download it, put it in a folder on your website, and use your own link in that case.)

<html>  <head>    <title>Line Chart JS</title>    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-base.min.js"></script>    <style type="text/css">            html, body, #container {         width: 100%; height: 100%; margin: 0; padding: 0;       }     </style>  </head>  <body>      <div id="container"></div>    <script>      // JavaScript code for the line chart.    </script>  </body></html>

The JavaScript code for the line graph will be inserted between <script> and </script> tags located in the <body> section (you may put those in the <head> section if you want).

3. Add your data

Then, add the data you want to visualize in your line chart.

I counted all Grand Slam singles titles won by Federer, Nadal, and Djokovic, by year. I will add it just like that as an array of arrays.

If you prefer other formats in your particular case, such as JSON, XML, CSV, or something else, check the ways to work with data.

var data = [  ["2003", 1, 0, 0],  ["2004", 4, 0, 0],  ["2005", 6, 0, 0],  ["2006", 9, 1, 0],  ["2007", 12, 2, 0],  ["2008", 13, 5, 1],  ["2009", 15, 6, 1],  ["2010", 16, 9, 1],  ["2011", 16, 10, 4],  ["2012", 17, 11, 5],  ["2013", 17, 13, 6],  ["2014", 17, 14, 7],  ["2015", 17, 14, 10],  ["2016", 17, 14, 12],  ["2017", 19, 16, 12],  ["2018", 20, 17, 14],  ["2019", 20, 19, 16],  ["2020", 20, 20, 17],  ["2021", 20, 20, 20],  ["2022", 20, 22, 20]];

In each array, the year is the first parameter (column #0). Then comes the number of titles won by the three players subsequently (cumulative for each).

4. Code a visualization

Now, the warm-up session is done, and the court is all set. So lets get the match started and do some quick JavaScript coding!

First, add anychart.onDocumentReady() as shown below:

<script>  anychart.onDocumentReady(function() {    // The main JS line charting code will be here.  });</script>

Everything else goes inside of that function.

So, second, include the data (from the previous step).

Third, create a data set and map it for each series (one for each player):

// create a data setvar dataSet = anychart.data.set(data);// map the data for all seriesvar firstSeriesData = dataSet.mapAs({x: 0, value: 1});var secondSeriesData = dataSet.mapAs({x: 0, value: 2});var thirdSeriesData = dataSet.mapAs({x: 0, value: 3});

Fourth, create a line chart instance and three series with the mapped data:

// create a line chartvar chart = anychart.line();// create the series and name themvar firstSeries = chart.line(firstSeriesData);firstSeries.name("Roger Federer");var secondSeries = chart.line(secondSeriesData);secondSeries.name("Rafael Nadal");var thirdSeries = chart.line(thirdSeriesData);thirdSeries.name("Novak Djokovic");

Fifth, to make it clear at a glance what is shown in the line chart, a good idea is to add a legend and a title:

// add a legendchart.legend().enabled(true);// add a titlechart.title("Big Three's Grand Slam Title Race");

Finally, reference the container element ID and draw the resulting line chart:

// specify where to display the chartchart.container("container");// draw the resulting chartchart.draw();

Thats it! A fully functional line graph built with JS is ready. Feels like a straight-sets victory, doesnt it?

Image description

Check out this basic version of the line chart with the full HTML/CSS/JS code on CodePen [or on AnyChart Playground]. Just in case, heres the code too:

<html>  <head>    <title>Line Chart JS</title>    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-base.min.js"></script>    <style type="text/css">            html, body, #container {         width: 100%; height: 100%; margin: 0; padding: 0;       }     </style>  </head>  <body>      <div id="container"></div>    <script>      anychart.onDocumentReady(function () {        // add data        var data = [          ["2003", 1, 0, 0],          ["2004", 4, 0, 0],          ["2005", 6, 0, 0],          ["2006", 9, 1, 0],          ["2007", 12, 2, 0],          ["2008", 13, 5, 1],          ["2009", 15, 6, 1],          ["2010", 16, 9, 1],          ["2011", 16, 10, 4],          ["2012", 17, 11, 5],          ["2013", 17, 13, 6],          ["2014", 17, 14, 7],          ["2015", 17, 14, 10],          ["2016", 17, 14, 12],          ["2017", 19, 16, 12],          ["2018", 20, 17, 14],          ["2019", 20, 19, 16],          ["2020", 20, 20, 17],          ["2021", 20, 20, 20],          ["2022", 20, 22, 20]        ];        // create a data set        var dataSet = anychart.data.set(data);        // map the data for all series        var firstSeriesData = dataSet.mapAs({x: 0, value: 1});        var secondSeriesData = dataSet.mapAs({x: 0, value: 2});        var thirdSeriesData = dataSet.mapAs({x: 0, value: 3});        // create a line chart        var chart = anychart.line();        // create the series and name them        var firstSeries = chart.line(firstSeriesData);        firstSeries.name("Roger Federer");        var secondSeries = chart.line(secondSeriesData);        secondSeries.name("Rafael Nadal");        var thirdSeries = chart.line(thirdSeriesData);        thirdSeries.name("Novak Djokovic");        // add a legend        chart.legend().enabled(true);        // add a title        chart.title("Big Three's Grand Slam Title Race");        // specify where to display the chart        chart.container("container");        // draw the resulting chart        chart.draw();      });    </script>  </body></html>

How to Customize Your Line Charts

The basic line chart we created by following the four steps above already looks good. But what if you want to customize it?

Let me show you how to make some changes in the same quick and easy manner.

  1. Name the axes.
  2. Customize the markers.
  3. Enable crosshairs.
  4. Change the tooltip position.
  5. Change the colors.
  6. Improve the title and legend text.
  7. Transform to a Stepped Line Chart.

FOR A WALKTHROUGH OF THESE JS LINE CHART CUSTOMIZATIONS, CONTINUE READING THE TUTORIAL HERE.


Original Link: https://dev.to/andreykh1985/how-to-create-a-line-chart-in-javascript-176k

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To