How to Create an Angular Gauge Using JavaScript

AnyChart
JavaScript in Plain English
13 min readFeb 3, 2021

--

An Angular Gauge, also known as a Circular Gauge, is a type of gauge chart with a radial scale. Such visualizations can nicely show a value within a range and are widely used in various dashboards.

The recent good news of vaccines feels like music to our ears. So, I thought why not take some interesting music data for visualization in this tutorial! The 63rd annual Grammy Awards ceremony will be held in March 2021, and when I looked through the list of the Record of the Year nominees, I wondered how popular each of these songs is. To find out, I decided to look at the number of their streams on Spotify, one of the world’s leading music streaming platforms, and thought that a Solid Angular Gauge could work well in such a visual analysis. It also resembles a vinyl record, which makes it an especially interesting chart type to opt for when representing such data!

So, along the tutorial, I will be visualizing Spotify stream counts for each 2021 GRAMMYs Record of the Year nominee song in a JS Angular Gauge chart. That is going to be entertaining! All aboard!

Before we get down to the process, check out how the final interactive JavaScript angular gauge chart will look:

Skills with web development and technologies like HTML and JavaScript are always helpful in interactive data visualization. But in fact, here you don’t even need much technical knowledge and experience. The thing is, creating JS angular gauges for a web site or app is not rocket science.

Basically, there are 4 fundamental steps to build an angular gauge using JavaScript:

  1. Create an HTML page.
  2. Include the necessary JavaScript files.
  3. Connect the data.
  4. Write the JS code for the chart.

1. Create a basic HTML page

The first thing to do is to make an HTML page where the angular gauge visualization will be rendered.

We add a div element to hold the chart and provide it with an id to properly reference this div later.

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Angular Gauge</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, the div block element is given a width and height of 100% to make the gauge chart appear full screen. But it can be customized according to your requirements, of course.

2. Include the necessary JavaScript files

The second step is about referencing the necessary scripts you are going to use, in the <head> section.

Some of the JavaScript charting libraries can make it really easy to create stunning graphics and diagrams visualizing data without much difficulty. In this tutorial, I am using AnyChart which is a lightweight, flexible, and easy-to-use JavaScript charting library. It supports angular gauges out of the box and has extensive documentation. In addition, AnyChart JS provides a cool code playground for testing out things.

So, let’s include the necessary files from this library’s CDN. To create an angular gauge, we need to add the core module that is required for all types of charts and the specific module for angular gauges.

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Venn Diagram</title>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-circular-gauge.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 angular gauge chart will come here
</script>
</body>
</html>

3. Prepare and connect the data

Step three is about data.

I created the data for this visualization manually by collating what I wanted from the official sources of the Grammys website and the Spotify app. I included the Song name, Artist name, Number of Spotify Streams, and Duration of each song.

I then sorted the data in descending order based on the number of streams and added a percentage field. The highest streamed record was given 100% and the percentage for the following records was calculated in comparison to the highest streamed record.

Finally, I created a JSON file which you can download here.

Loading the JSON data in AnyChart can be done with the help of the Data Adapter, an additional helpful script available through the dedicated module. Let’s reference it along with all the JS scripts in <head>.

Next, we use the loadJsonFile method inside the <script> tag in the body of our HTML page to load the JSON file.

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Angular Gauge</title>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-circular-gauge.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-data-adapter.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.data.loadJsonFile('{JSON data file location here}', function (data) {
// The angular gauge's JS code will come here
});
</script>
</body>
</html>

Now that we have all the preliminary steps taken care of, let’s amp up our excitement and start adding the code to visualize the data in an interactive JS-based angular gauge!

4. Add the JS code for the gauge

To build any JS chart or gauge, it is necessary to add a function enclosing all the code, which will make sure that the entire code inside of it will only execute once the page is ready.

The solid angular gauge we are creating right now is slightly more complicated to build than other chart types like a bar, pie, or area chart. But, do not worry as all the code is commented and I will also guide you through the code snippets. In case it still feels confusing, just follow the steps and you will be able to drum up a lovely chart in no time. Ask questions if any, in the post comments.

To begin with, we extract the data values required for the radial bars, create the angular gauge, and pass the extracted data to the chart.

<script>anychart.onDocumentReady(function () {anychart.data.loadJsonFile('https://gist.githubusercontent.com/shacheeswadia/9e4598a73bb86180f1726daf9de8062f/raw/b258e93e1f9db37da6847eb05a230afcb64446d5/circularGaugeData.json', function (data) {  // Get the names of the records 
var recordNames = data.map(function(d){
return d.Record;
});
// Get the percent values
var recordPercentValue = data.map(function(d){
return d.percent;
});
// Add the 100% value to signify the max value for each of the radial ring
recordPercentValue.push(100);
// Set the data to indicate the percent values
var dataSet = anychart.data.set(recordPercentValue);
// Create the angular gauge
var gauge = anychart.gauges.circular();
// Set the data for the angular gauge
gauge.data(dataSet);
});});</script>

I want each data point to have a different color. So, let’s up a color palette. Initially, we can use the default colors of the AnyChart JavaScript charting library.

Next, we specify the attributes of the gauge and create the axis. I do not want to show the axis labels and ticks so let’s hide those.

// Set the colors based on the default palette
var palette = anychart.palettes
.distinctColors()
.items([
'#64b5f6', '#1976d2', '#ef6c00', '#ffd54f', '#455a64', '#dd2c00', '#00838f', '#00bfa5', '#96a6a6', '#ffa000'
]);
// Specify the attributes of the angular gauge chart
gauge
.fill('#fff')
.stroke(null)
.padding(25, 100, 25, 100)
.margin(0)
.startAngle(0)
.sweepAngle(270);
// Create the angular gauge axis
var axis = gauge.axis().radius(100).width(1).fill(null);
// Set the minimum and maximum values for the axis
axis
.scale()
.minimum(0)
.maximum(100);
// Hide the axis labels and ticks
axis.labels().enabled(false);
axis.ticks().enabled(false);
axis.minorTicks().enabled(false);

Now comes the main part of creating the radial bars of the angular gauge. We create a function that accepts the gauge, index of each radial bar along with the radius, and the width of the radial bar as the parameters. We then build each bar based on the data point and also a background radial bar of each of those points.

Next, we set up the labels and align them to correspond to each radial bar. The last thing in the function is to return a gauge for each of the data points.

// Create a function to make radial bars for each data point
var makeBarWithBar = function (gauge, radius, i, width) {
// Create the radial bars based on the data
gauge
.bar(i)
.dataIndex(i)
.radius(radius)
.width(width)
.fill(palette.itemAt(i))
.stroke(null)
.zIndex(5);
// Create the background radial bars indicating the total value
gauge
.bar(i + 100)
.dataIndex(8)
.radius(radius)
.width(width)
.fill('#F5F4F4')
.stroke(null)
.zIndex(4);
// Set the labels based on each data point
gauge
.label(i)
.text(recordNames[i]);
// Align the labels
gauge
.label(i)
.hAlign('center')
.vAlign('middle')
.anchor('right-center')
.padding(0, 10)
.height(width / 2 + '%')
.offsetY(radius + '%')
.offsetX(0);
return gauge.bar(i);};

Now that the function is created, we call the function for each of the data points that we have. In total, there are 8 data points. So we call the function 8 times. The radius values are 100 divided by the number of data points, and I keep the width of each bar as 11.

// Call the function to create the radial bars with specifications
makeBarWithBar(gauge, 100, 0, 11);
makeBarWithBar(gauge, 87.5, 1, 11);
makeBarWithBar(gauge, 75, 2, 11);
makeBarWithBar(gauge, 62.5, 3, 11);
makeBarWithBar(gauge, 50, 4, 11);
makeBarWithBar(gauge, 37.5, 5, 11);
makeBarWithBar(gauge, 25, 6, 11);
makeBarWithBar(gauge, 12.5, 7, 11);

We then add a title to the chart. Finally, we reference the div container and draw our angular gauge.

// Add the angular gauge chart title
gauge.title('Comparing Popularity of 2021 GRAMMYs Record of the Year Nominations on Spotify');
// Drawing the resulting angular gauge
gauge.container('container');
gauge.draw();

There you have it — a fully functional and cool JavaScript-based Angular Gauge is ready! Or you can call it a Circular Gauge or a Radial Gauge — whichever you prefer.

We can clearly see from our Angular Gauge that there is quite a huge difference in the popularity of these tracks. Dua Lipa’s “Don’t Start Now” is the most-streamed song from the list of the 2021 Grammys Record of the Year nominees with a whooping 1.26 billion streams on Spotify, closely followed by Post Malone’s “Circles” with 1.24 billion streams. These two are the definite leaders by this parameter. Does it mean one of them will win? Hmm… (Not necessarily, you know.)

The song “Colors” by Black Pumas does have an impressive total of 36 million streams but ends up as the least-streamed song in this group.

Have a look at this initial version of the Angular Gauge with the full JS/CSS/HTML code on Playground or CodePen.

JavaScript Angular Gauge Customization

Robust JavaScript libraries for data visualization not only simplify chart creation but also provide flexibility to make customizations. With a few code tweaks, we can make some quick and effective changes to our circular graphic.

Let us look at some different functionalities and aesthetics for the angular gauge.

Change the color palette

Since our data is about Grammys nominations, I decided to use the colors resembling the gilded gramophone trophies and introduce the corresponding palette. We have already created a palette with distinct colors, so let’s just replace the default colors with the new ones.

// Set the colors based on the designated palette
var palette = anychart.palettes
.distinctColors()
.items([
'#593d04', '#6c4304', '#966905', '#a77b0a', '#cf9f20', '#ddb22e', '#f1c84d', '#ffdc73'
]);

See how the chart looks much more personalized — here’s the Angular Gauge built with JS, now with these modifications:

Check it out on Playground or CodePen.

Set a custom bar sizing

Now, let’s experiment a bit with the radial bars and add some more information to the current chart.

For example, we can make the width of each bar represent the song duration.

To do that, we need to extract the duration of each song from the data and then create a loop that makes the width of each bar correspond to the duration of that data point.

// Get the time of each song
var recordLength = data.map(function(d){
return d['Time'];
});
// Call the function to create the radial bars with specifications
for(var i=0, j=100; i<data.length, j>=12.5; i++, j-=12.5){
makeBarWithBar(gauge, j, i, (recordLength[i]* 2.75));
}

Check out how the variation looks:

You can find this version with the entire code on Playground or CodePen.

Ultimately I did not find it very insightful and reverted to the version with a fixed width for each bar. I did keep the loop though since that reduces the amount of the code and is a better way of calling the function repeatedly.

Improve the design of the angular gauge tooltip and other formatting

The JavaScript angular gauge we’ve made already looks great. All we may need are some finishing touches.

Let’s design a good-looking and informative tooltip.

To start with, please note changes here:

// Add the 100% value to signify the max value for each of the radial ring
var initialLength = recordPercentValue.length;
recordPercentValue.length *= 2;
recordPercentValue.fill(100, initialLength);
...// Create the background radial bars indicating the total value
gauge
.bar(i + 100)
.dataIndex(initialLength + I)
.radius(radius)
.width(width)
.fill('#F5F4F4')
.stroke(null)
.zIndex(4);

And we add the following part:

// Angular gauge tooltip
gauge.tooltip().useHtml(true);

// Format the information of the tooltip
gauge
.tooltip()
.format(function(){
var index = this.index;
if (index >= initialLength)
index -= initialLength;
return "<div style='font-size:15px; font-weight:400; margin: 0.2rem 0; color: #1db954; padding:0.15rem'>Record: <span style='color:#fff;'>" + data[index]['Record'] + "</span></div><div style='font-size:15px; font-weight:400; margin: 0.2rem 0; color: #1db954; padding:0.15rem'>Artist: <span style='color:#fff;'>" + data[index]['Artist'] + "</span></div><div style='font-size:15px; font-weight:400; margin: 0.2rem 0; color: #1db954; padding:0.15rem'>Number of Spotify Streams: <span style='color:#fff;'>" + Intl.NumberFormat().format(data[index]['StreamsSpotify']) + "</span></div><div style='font-size:15px; font-weight:400; margin: 0.2rem 0; color: #1db954; padding:0.15rem'>Comparitive Popularity: <span style='color:#fff;'>" + data[index]['percent'] + "%</span></div>";
});

Lastly, that should be great to beautify the title with larger fonts and apply some color changes to highlight exactly what we are showing:

// Add the angular gauge chart title
gauge
.title()
.useHtml(true)
.text(
'<span style = "color: #4c2b04; font-size:20px;">Comparing Popularity of 2021 GRAMMYs Record of the Year Nominations</span>' +
'<br/><span style="color:#1db954; font-size: 18px;">(Based on the number of Spotify Streams)</span>'
);

You can find the full source code for this final Angular Gauge here below as well as look into it and play with it on Playground or on CodePen.

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Angular Gauge</title>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-circular-gauge.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-data-adapter.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 () {anychart.data.loadJsonFile('https://gist.githubusercontent.com/shacheeswadia/9e4598a73bb86180f1726daf9de8062f/raw/b258e93e1f9db37da6847eb05a230afcb64446d5/circularGaugeData.json', function (data) { // Get the names of the records
var recordNames = data.map(function(d){
return d.Record;
});
// Get the percent values
var recordPercentValue = data.map(function(d){
return d.percent;
});
// Add the 100% value to signify the max value for each of the radial ring
var initialLength = recordPercentValue.length;
recordPercentValue.length *= 2;
recordPercentValue.fill(100, initialLength);
// Set the data to indicate the percent values
var dataSet = anychart.data.set(recordPercentValue);
// Create the angular gauge
var gauge = anychart.gauges.circular();
// Set the data for the angular gauge
gauge.data(dataSet);

// Set the colors based on the designated palette
var palette = anychart.palettes
.distinctColors()
.items([
'#593d04', '#6c4304', '#966905', '#a77b0a', '#cf9f20', '#ddb22e', '#f1c84d', '#ffdc73'
]);
// Specify the attributes of the angular gauge chart
gauge
.fill('#fff')
.stroke(null)
.padding(25, 100, 25, 100)
.margin(0)
.startAngle(0)
.sweepAngle(270);
// Create the angular gauge axis
var axis = gauge.axis().radius(100).width(1).fill(null);
// Set the minimum and maximum values for the axis
axis
.scale()
.minimum(0)
.maximum(100);
// Hide the axis labels and ticks
axis.labels().enabled(false);
axis.ticks().enabled(false);
axis.minorTicks().enabled(false);
// Create a function to make radial bars for each data point
var makeBarWithBar = function (gauge, radius, i, width) {
// Create the radial bars based on the data
gauge
.bar(i)
.dataIndex(i)
.radius(radius)
.width(width)
.fill(palette.itemAt(i))
.stroke(null)
.zIndex(5);
// Create the background radial bars indicating the total value
gauge
.bar(i + 100)
.dataIndex(initialLength + i)
.radius(radius)
.width(width)
.fill('#F5F4F4')
.stroke(null)
.zIndex(4);
// Set the labels based on each data point
gauge
.label(i)
.text(recordNames[i]);
// Align the labels
gauge
.label(i)
.hAlign('center')
.vAlign('middle')
.anchor('right-center')
.padding(0, 10)
.height(width / 2 + '%')
.offsetY(radius + '%')
.offsetX(0);
return gauge.bar(i); }; // Angular gauge tooltip
gauge.tooltip().useHtml(true);

// Format the information of the tooltip
gauge
.tooltip()
.format(function(){
var index = this.index;
if (index >= initialLength)
index -= initialLength;
return "<div style='font-size:15px; font-weight:400; margin: 0.2rem 0; color: #1db954; padding:0.15rem'>Record: <span style='color:#fff;'>" + data[index]['Record'] + "</span></div><div style='font-size:15px; font-weight:400; margin: 0.2rem 0; color: #1db954; padding:0.15rem'>Artist: <span style='color:#fff;'>" + data[index]['Artist'] + "</span></div><div style='font-size:15px; font-weight:400; margin: 0.2rem 0; color: #1db954; padding:0.15rem'>Number of Spotify Streams: <span style='color:#fff;'>" + Intl.NumberFormat().format(data[index]['StreamsSpotify']) + "</span></div><div style='font-size:15px; font-weight:400; margin: 0.2rem 0; color: #1db954; padding:0.15rem'>Comparitive Popularity: <span style='color:#fff;'>" + data[index]['percent'] + "%</span></div>";
});
// Call the function to create the radial bars with specifications
for(var i=0, j=100; i<data.length, j>=12.5; i++, j-=12.5){
makeBarWithBar(gauge, j, i, 12);
}
// Add the angular gauge chart title
gauge
.title()
.useHtml(true)
.text(
'<span style = "color: #4c2b04; font-size:20px;">Comparing Popularity of 2021 GRAMMYs Record of the Year Nominations</span>' +
'<br/><span style="color:#1db954; font-size: 18px;">(Based on the number of Spotify Streams)</span>'
);
gauge
.title()
.enabled(true)
.hAlign('center')
.padding(0)
.margin([0, 0, 10, 0]);

// Drawing the resulting angular gauge
gauge.container('container');
gauge.draw();
});}); </script>
</body>
</html>

Conclusion

In this step-by-step tutorial, I have shown you in detail how to create a compelling Angular Gauge with JavaScript (HTML5). As you can see, creating interactive JS charts is easy.

You can try out other JavaScript charting libraries and gauge their capability in creating the data visualizations you need. Or you can check out various other chart options provided by AnyChart. For inspiration, you might like to visit the library’s gallery for basic chart types. Please feel free to ask me any questions or let me know how your JS gauge turned out.

Wishing you a healthy, musical, and visual 2021!

We at AnyChart are glad to thank Shachee Swadia, an experienced data designer, for creating this amazing tutorial. Check out other JavaScript charting tutorials.

Originally published at https://www.anychart.com on February 3, 2021.

--

--

Cross-platform JavaScript/HTML5 data visualization solutions, flexible JS charts libraries & Qlik Sense extensions for all your data viz needs: www.anychart.com