How to Build a JavaScript Line Chart | by AnyChart | Jul, 2021


A line chart is one of the basic and most commonly used techniques of data visualization. Such graphics are known to provide an informative look at the change of one or several variables over time. Right now, I’ll explain how to easily create a cool interactive line chart using JavaScript!

The process will be demonstrated with the help of compelling examples that you can play with afterwards to hone your new data visualization development skills.

To make the article especially thrilling for you to read and learn from, I decided to showcase a practical application of a line chart to real-world data. The month of June was celebrated as Pride Month, and I thought it would be great to see how attitudes toward LGBT people have changed over the recent years. Then I found interesting public opinion data from the General Social Survey (GSS), a project of the National Opinion Research Center (NORC) at the University of Chicago, which appeared to be a good fit, and took part of it to visualize in this guide.

So, follow along with the tutorial and you will also be able to explore the shifts in acceptance of same-sex relationships in the United States over the last two decades! We will create a single-series JS line chart first, representing the general trend, and then a multi-series JS line chart to visualize a breakdown by age group.

All aboard!

Doesn’t it feel great to look at this colorful chart and feel positive about the future outlook?

Read this step-by-step tutorial all the way to the end and you will learn how to produce such a line graph easily with very little coding.

  1. Creating a basic HTML page to display the chart.
  2. Including all the JS scripts we need.
  3. Adding the data for the chart.
  4. Writing the JS charting code.

So now, let’s dig into each of these steps to draw our line chart in a jiffy.

1. Creating a basic HTML page

<html>
<head>
<title>JavaScript Line Chart</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>

Here, we provide the <div> with the 100% width and height to render the line chart on the full screen. But it’s not necessary and can be customized according to your requirements, of course.

2. Including all the JS scripts

In this tutorial, the line chart is built with AnyChart. It is a lightweight and flexible JavaScript (HTML5) charting library with detailed documentation and API reference. In addition, there are a lot of chart examples to check out and use as the starting point, as well as a utility called Playground to experiment with the code.

Since the line chart is one of the basic chart types, it requires only the base module of AnyChart. We can easily obtain it from the CDN. The JS line chart code itself will be written in the <script> tag inside of the <body> section.

<html>
<head>
<title>JavaScript Line Chart</title>
<script src="https://cdn.anychart.com/releases/8.10.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>
// All the code for the JS line chart will come here
</script>
</body>
</html>

3. Adding the data

AnyChart supports multiple options to load data to charts. The data set for our line chart is pretty straightforward and not large at all. So we can simply include it inside the code itself.

To do that, we create a function that will return the data to keep it as a separate block of code.

function getData() {
return [
['1990',12],
['1991',14],
['1993',21],
['1994',21],
['1996',26],
['1998',26],
['2000',27],
['2002',31],
['2004',29],
['2006',31],
['2008',36],
['2010',41],
['2012',42],
['2014',48],
['2016',50],
['2018',57]
];
}

All the prep is done and now it’s time to create the line chart with a few lines of JavaScript code!

4. Writing the JS line charting code

We set up the data by calling the function we made in the previous step, and then we map the data to indicate that the first parameter for every data point is the X value and the second parameter is the Y value. Next, we call the line() function to create the JS line chart.

// create a data set on our data
var dataSet = anychart.data.set(getData());
// map data for the line chart,
// take x from the zero column and value from the first column
var seriesData = dataSet.mapAs({ x: 0, value: 1 });
// create a line chart
var chart = anychart.line();

Now, we set the titles for the line chart and for the Y-axis.

// configure the chart title text settings
chart.title('Acceptance of same-sex relationships in the US over the last 2 decades');
// set the y axis title
chart.yAxis().title('% of people who accept same-sex relationships');

Lastly, we load the mapped data to the line chart, set the container id, and draw the graphic.

// create a line series with the mapped data
var lineChart = chart.line(seriesData);
// set the container id for the line chart
chart.container('container');
// draw the line chart
chart.draw();

Voilà! A functional, interactive, JavaScript-based line chart is created! This was quite quick and simple, wasn’t it?

Check out the result below, and you are more than welcome to see this chart and play with its code on AnyChart Playground.

https://playground.anychart.com/AMYKy0zt/

What does this line chart tell us? We can clearly see the positive change over time and how the acceptance of same-sex relationships in the United States was gradually increasing between 1990 and 2018 with just a few slight pauses.

But do not leave yet! Although this chart already looks good, it is just a very basic version of the JS line chart we can afford to obtain. It will only take a few more steps to add functionality and interactivity.

Now, get ready to make a stunning multi-line chart that will visualize a breakdown by age!

The basic code remains the same. But instead of one series, we will create multiple series. Of course, the data will contain multiple data points for each year now as we break down the total percentage for “Not wrong at all” by age groups: 18–34, 35–49, 50–64, and 65+.

function getData() {
return [
['1990',16.9,12.2,10.2,5.2],
['1991',17,17.8,10,4.8],
['1993',26.5,23.8,16.8,6.6],
['1994',28.7,22,17.3,9.1],
['1996',35.7,24,22.6,9.2],
['1998',37.2,24.6,22.4,11.2],
['2000',36.5,26.2,23.7,9.9],
['2002',40,34.4,23.8,16.4],
['2004',33.3,28.8,32.5,14.3],
['2006',40.2,32.1,27.5,15.1],
['2008',49.3,37.2,31.4,17.1],
['2010',51.9,42.5,36.1,28.5],
['2012',53.1,43.8,36,24.6],
['2014',63.7,45.9,44.7,31.3],
['2016',66.3,52,42.3,37.2],
['2018',70.1,57.7,49.2,39]
];
}

We will need to create a different data mapping for each series.

// map data for the first series,
// take x from the zero column and value from the first column
var firstSeriesData = dataSet.mapAs({ x: 0, value: 1 });
// map data for the second series,
// take x from the zero column and value from the second column
var secondSeriesData = dataSet.mapAs({ x: 0, value: 2 });
// map data for the third series,
// take x from the zero column and value from the third column
var thirdSeriesData = dataSet.mapAs({ x: 0, value: 3 });

// map data for the fourth series,
// take x from the zero column and value from the fourth column
var fourthSeriesData = dataSet.mapAs({ x: 0, value: 4 });

We then link each of those series to a different line and name each series based on the segments.

// create the first series with the mapped data
var firstSeries = chart.line(firstSeriesData);
firstSeries.name('18-34');
// create the second series with the mapped data
var secondSeries = chart.line(secondSeriesData);
secondSeries.name('35-49');
// create the third series with the mapped data
var thirdSeries = chart.line(thirdSeriesData);
thirdSeries.name('50-64');

// create the fourth series with the mapped data
var fourthSeries = chart.line(fourthSeriesData);
fourthSeries.name('65+');

Here, since we have multiple lines depicted in our JS line plot, we need a legend that will help identify which line represents what segment. Don’t worry, it’s nothing complex. The chart legend is automatically created by the JS library and we just need to turn it on.

// turn the legend on
chart.legend().enabled(true);

That’s it! With these simple modifications, we get a lovely-looking multi-series line chart built with JavaScript! It can also be viewed and further played with on AnyChart Playground.

https://playground.anychart.com/1tvaNdD6/

Again, we can distinctly grasp how the overall trend is positive in all age groups, especially in the younger generation.

So, let’s make some quick tweaks to have a more insightful view of the data.

1. Smoothening the lines

// create the first series with the mapped data
var firstSeries = chart.spline(firstSeriesData);
firstSeries.name('18-34');
// create the second series with the mapped data
var secondSeries = chart.spline(secondSeriesData);
secondSeries.name('35-49');
// create the third series with the mapped data
var thirdSeries = chart.spline(thirdSeriesData);
thirdSeries.name('50-64');

// create the fourth series with the mapped data
var fourthSeries = chart.spline(fourthSeriesData);
fourthSeries.name('65+');

After these simple changes, our line chart becomes a spline chart!

2. Adding crosshair on hover for each data point

// turn on the crosshair
chart.crosshair().enabled(true).yLabel(false).yStroke(null);

Check out the interactive JavaScript spline chart with the crosshair! It is available on AnyChart Playground.

https://playground.anychart.com/7l7UhiWw

Ultimately, for the final chart of this JS line chart tutorial, let’s go ahead with straight lines instead of smooth curves. But we’ll keep the crosshair anyway.

3. Improving the JS line chart tooltip

This can be simply done by setting the format() function for the tooltip in each line series. Here’s an example for the first one:

firstSeries
.tooltip()
.format("Age group 18-34 : {%value}%");

4. Changing the colors and other aesthetics

Let’s also make the lines a bit thicker so they look more pronounced. Modifying the color and the line width can be done together using the stroke attribute in the settings of each series. Like this:

firstSeries
.stroke('3 #f49595')

Lastly, we add a simple animation to jazz up the line chart, which is again done very easily as the JavaScript library has it as a pre-built feature.

// turn on the line chart animation
chart.animation(true);

It’s done! A stunning, interactive JavaScript line chart is all wrapped up!

For your convenience, the final HTML/CSS/JS line chart code is below the visualization. Don’t hesitate to check it out on AnyChart Playground and maybe apply your data and other changes.

https://playground.anychart.com/4L1XeREM/
<html>
<head>
<title>JavaScript Line Chart</title>
<script src="https://cdn.anychart.com/releases/8.10.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 () { // create a data set on our data
var dataSet = anychart.data.set(getData());

// map data for the first series,
// take x from the zero column and value from the first column
var firstSeriesData = dataSet.mapAs({ x: 0, value: 1 });

// map data for the second series,
// take x from the zero column and value from the second column
var secondSeriesData = dataSet.mapAs({ x: 0, value: 2 });

// map data for the third series,
// take x from the zero column and value from the third column
var thirdSeriesData = dataSet.mapAs({ x: 0, value: 3 });

// map data for the fourth series,
// take x from the zero column and value from the fourth column
var fourthSeriesData = dataSet.mapAs({ x: 0, value: 4 });

// create a line chart
var chart = anychart.line();
// turn on the line chart animation
chart.animation(true);

// configure the chart title text settings
chart.title('Acceptance of same-sex relationships in the US over the last 2 decades');

// set the y axis title
chart.yAxis().title('% of people who accept same-sex relationships');

// turn on the crosshair
chart.crosshair().enabled(true).yLabel(false).yStroke(null);

// create the first series with the mapped data
var firstSeries = chart.line(firstSeriesData);
firstSeries
.name('18-34')
.stroke('3 #f49595')
.tooltip()
.format("Age group 18-34 : {%value}%");

// create the second series with the mapped data
var secondSeries = chart.line(secondSeriesData);
secondSeries
.name('35-49')
.stroke('3 #f9eb97')
.tooltip()
.format("Age group 35-49 : {%value}%");

// create the third series with the mapped data
var thirdSeries = chart.line(thirdSeriesData);
thirdSeries
.name('50-64')
.stroke('3 #a8d9f6')
.tooltip()
.format("Age group 50-64 : {%value}%");

// create the fourth series with the mapped data
var fourthSeries = chart.line(fourthSeriesData);
fourthSeries
.name('65+')
.stroke('3 #e2bbfd')
.tooltip()
.format("Age group 65+ : {%value}%");

// turn the legend on
chart.legend().enabled(true);
// set the container id for the line chart
chart.container('container');

// draw the line chart
chart.draw();

});function getData() {
return [
['1990',16.9,12.2,10.2,5.2],
['1991',17,17.8,10,4.8],
['1993',26.5,23.8,16.8,6.6],
['1994',28.7,22,17.3,9.1],
['1996',35.7,24,22.6,9.2],
['1998',37.2,24.6,22.4,11.2],
['2000',36.5,26.2,23.7,9.9],
['2002',40,34.4,23.8,16.4],
['2004',33.3,28.8,32.5,14.3],
['2006',40.2,32.1,27.5,15.1],
['2008',49.3,37.2,31.4,17.1],
['2010',51.9,42.5,36.1,28.5],
['2012',53.1,43.8,36,24.6],
['2014',63.7,45.9,44.7,31.3],
['2016',66.3,52,42.3,37.2],
['2018',70.1,57.7,49.2,39]
];
}

For a deeper look at how to build and personalize JS line charts, see the line chart documentation. Also, don’t miss out on checking out these line chart examples for inspiration.

If you have any questions about the JavaScript line charts built in this tutorial, or the line chart type in general, or any specific features you are not sure how to implement, please leave them in the comments and I will do my best to provide timely responses.

Let us all be proud of who we are and add this chart into the data visualization development skillset to flaunt!



Source link

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here