DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for How to Create a Line Chart in JavaScript
andreykh1985
andreykh1985

Posted on • Originally published at anychart.com

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). It’s 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. We’ll 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 Three’s 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.

Let’s 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 don’t 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.

Here’s 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>
Enter fullscreen mode Exit fullscreen mode

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 we’ll 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. It’s 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>
Enter fullscreen mode Exit fullscreen mode

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]
];
Enter fullscreen mode Exit fullscreen mode

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 let’s 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>
Enter fullscreen mode Exit fullscreen mode

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 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});
Enter fullscreen mode Exit fullscreen mode

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

// 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");
Enter fullscreen mode Exit fullscreen mode

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 legend
chart.legend().enabled(true);

// add a title
chart.title("Big Three's Grand Slam Title Race");
Enter fullscreen mode Exit fullscreen mode

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

// specify where to display the chart
chart.container("container");

// draw the resulting chart
chart.draw();
Enter fullscreen mode Exit fullscreen mode

That’s it! A fully functional line graph built with JS is ready. Feels like a straight-sets victory, doesn’t 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, here’s 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>
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (3)

Collapse
 
lukeshiru profile image
Luke Shiru

Hi there, we encourage authors to share their entire posts here on DEV, rather than mostly pointing to an external link. Doing so helps ensure that readers don’t have to jump around to too many different pages, and it helps focus the conversation right here in the comments section.

If you choose to do so, you also have the option to add a canonical URL directly to your post.

Collapse
 
jonrandy profile image
Jon Randy • Edited on

This is really more a "how to include a library, and call a function" tutorial, than a tutorial on how to draw a line graph in JS.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post