JavaScript

How to Create a Simple Graph in JavaScript

Graphs are better than textual data to show some sort of survey or to categorize raw data. Users can create graphs with the help of different SVG elements grouped to showcase data. In HTML <svg> is used to display an SVG element and a <g> tag is used to group multiple SVG elements together. However, using JavaScript to compute elements that we have to categorize in the graph and then display them in a linear graph chart is quite complex.

This article will take an array of elements which are going to car makes and their quantity found in a survey. After that, it will calculate their percentages from the total cars in the survey and then display them on the graph with their percentages written on the linear graph.

Step 1: Setting up the HTML Document

The HTML doesn’t require much stuff to be done inside it. We simply need to create an empty <div> that will be modified by JavaScript code, and JavaScript will also plot the graph inside this div. Therefore, use the following lines:

<center>

<b>This is a Linear Graph Showcasing Percentages of Car Makes From a Survey<b>

<div id="graphDiv"></div>

</center>

At this point, the HTML document will only show the following result:

The div is not visible, because currently it doesn’t contain any other elements or text.

Step 2: Setting up the JavaScript Code

Start by creating an element array. This array is going to contain the Name of the car make and the number of cars. For this, simply use the following lines:

let elementArray = [];

elementArray[0] = ["Mercedes", 8];

elementArray[1] = ["Audi", 13];

elementArray[2] = ["BMW", 11];

elementArray[3] = ["Porsche", 25];

After that, we are going to create a function that is going to plot the graph on the HTML document. This function will be named “plotGraph”, and it will take the three parameters as:

function plotGraph(array, graphWidth, div) {

// The next lines will be included in this body

}

As you can see, this function takes the element from which is going to pick in the raw data, it takes in the width of the graph on the HTML webpage and the div in which it has to plot the graph.

In this function, the very first thing is to create the following variables:

let totalCars = 0;

let calpercentage = 0;

let calwidth = 0;

The thing is:

  • total cars will be used to store the number of cars
  • calPercentage will be used to calculate the percentage of each car make
  • calwidth will be used to determine the size of the bar (according to the percentage) of the graph to be placed inside the width passed in the parameters

To calculate the total number of cars use the following lines of code:

for (i = 0; i < array.length; i++) {

totalCars += parseInt(array[i][1]);

}

After that, create a variable named as output, this variable will be used to create a table on the HTML webpage. Therefore, it will contain HTML code inside it:

let output = '<table border="0" cellspacing="0" cellpadding="8">';

Currently, this output variable only contains the query for the start of the table. Later on, more queries inside will be appended to it, which will represent the complete table with a graph inside it.

After that simply use the following lines of code:

for (i = 0; i < array.length; i++) {

calpercentage = Math.round((array[i][1] * 100) / totalCars);

calwidth = Math.round(graphWidth * (calpercentage / 100));

output += `<tr><td>${array[i][0]}</td><td><svg width="${calwidth}" height="10"><g class="bar"><rect width="${calwidth}" height="10"></rect></g></svg> ${calpercentage}%</td></tr>`;

}

In the above code snippet:

  • This for loop is going to iterate through the elements array one by one
  • Percentages of every car make is being calculated
  • And then the size of the percentage bar is being calculated
  • Lastly, the output is being appended with the HTML query to compute the next bar of the graph
  • <svg> tag creates an SVG element on the HTML webpage
  • <g> groups SVG elements together under a given name

After this, simply come out of the for loop, and append the ending tag of the table inside the output variable

output += "</table>";

Now at this point, the output variable contains the complete HTML query to plot the linear graph from the raw data that was provided. All that is left to do is to access the div and set it equal to our output variable and also display the total number of cars:

div.innerHTML = `${output}<br>Total Cars: <b>${totalCars}</b>`;

And with that the function plotGrapgh is complete. To plot the graph, simply call the plotGraph function and pass in the arguments as:

plotGraph(elementArray, 500, document.getElementById("graphDiv"));

The complete JavaScript code is as:

let elementArray = [];

elementArray[0] = ["Mercedes", 8];

elementArray[1] = ["Audi", 13];

elementArray[2] = ["BMW", 11];

elementArray[3] = ["Porsche", 25];

function plotGraph(array, graphWidth, div) {

let totalCars = 0;

let calpercentage = 0;

let calwidth = 0;

for (i = 0; i < array.length; i++) {

totalCars += parseInt(array[i][1]);

}

let output = '<table border="0" cellspacing="0" cellpadding="8">';

for (i = 0; i < array.length; i++) {

calpercentage = Math.round((array[i][1] * 100) / totalCars);

calwidth = Math.round(graphWidth * (calpercentage / 100));

output += `<tr><td>${array[i][0]}</td><td><svg width="${calwidth}" height="10"><g class="bar"><rect width="${calwidth}" height="10"></rect></g></svg> ${calpercentage}%</td></tr>`;

}

output += "</table>";

div.innerHTML = `${output}<br>Total Cars: <b>${totalCars}</b>`;

}

plotGraph(elementArray, 500, document.getElementById("graphDiv"));

Running the HTML document on a web-browser now shows the following output:

And the linear graph has been plotted inside the div showcasing the percentages of different car makes from a survey.

Conclusion

It is possible to create a graph on an HTML document with the help of JavaScript. For this, the user needs to utilize the <svg> tag to create SVG elements and the <g> to group multiple SVG elements together under a specific name. However, it is not easy to build a graph on an HTML webpage as it can be very daunting for a new beginner. In this article, a linear graph was built with JavaScript, and each step was thoroughly explained.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.