This article provides an easy-to-follow guide for building interactive linear meter diagrams in the middle of JavaScript.

We’ll show you how to quickly create a cool interactive linear meter chart that highlights COVID-19 vaccination data around the world. Our charts will allow us to visualize the status of COVID-19 vaccination at the time of writing and will show two types of data — showing how far we are from our halfway goal of partially and fully vaccinating the global population.

What is a linear instrument diagram?

Given the amount of data being created and the many possibilities for gathering information from that data, data visualization is an invaluable tool. Data visualization is especially useful for identifying trends, explaining patterns, and communicating complex ideas to target audiences.

A linear meter diagram represents a vertical or horizontal linear scale with a color scale and one or more Pointers that display the desired values. The minimum and maximum values of the data range can be set on the axis based on the data represented. Pointer position indicates the current value of an indicator.

Meter diagrams can display a single value or multiple values using a single pointer or tag combination. A pointer can be a needle or line marked with any shape, such as a circle, square, rectangle, or triangle.

The linear meter chart type is an effective visual representation for showing the distance between values and desired data points.

Type of linear gauge

Several types of linear gauges are thermometer charts, bullet charts, tank charts and LED charts. A mercury thermometer — consisting of small scales showing temperature and pointer values — is a typical example of a linear meter diagram.

The linear instrumentation visualization we will build

This is a preview of the final linear instrumentation diagram. Follow this tutorial to learn how we built this interesting and informative linear meter diagram using JavaScript.

Four steps to building a JavaScript linear meter

Skills in technologies like HTML and JavaScript are always useful. But in this tutorial, we use a JS chart library that makes it easier to create eye-catching charts like linear meters, even with minimal technical knowledge.

There are several JavaScript charting libraries that make it easy to visualize data, and here we use AnyChart to create linear meter diagrams. The library is flexible and well-documented, and it contains some good examples. It also has a playground for testing code and is free for non-commercial use. If you would like to purchase a licensed version, you can view the available options, and if you are an educational institution or non-profit organization, you can contact here to obtain a free license.

Steps for making JavaScript linear meters

Here are the basic steps to create a linear meter diagram:

  1. Create a basic HTML page.
  2. Include the necessary JavaScript files.
  3. Add data.
  4. Write JavaScript code for the diagram.

Let’s look at each of these steps in detail below.

1. Create a basic HTML page

The first thing we need to do is create an HTML page to hold our visualization. Let’s add one

Block element and give it an ID so we can reference it later:

<html lang="en">
  <head>
    <title>JavaScript Linear 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>
Copy the code

Width and height properties of

Set it to 100% so that the chart is rendered throughout the screen. These properties can be modified as needed.

2. Include the necessary JavaScript files

The next step is to reference the JS link in the HTML page. We will be using the AnyChart library in this tutorial, so let’s include the corresponding files from their CDN. To create a linear meter diagram, we need to add three scripts: the core module, the linear meter module, and the table module:

<html lang="en"> <head> <title>JavaScript Linear Gauge</title> <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 linear gauge will come here < / script > < script SRC = "https://cdn.anychart.com/releases/8.10.0/js/anychart-core.min.js" > < / script > < script SRC = "https://cdn.anychart.com/releases/8.10.0/js/anychart-linear-gauge.min.js" > < / script > < script SRC = "https://cdn.anychart.com/releases/8.10.0/js/anychart-table.min.js" > < / script > < / body > < / HTML >Copy the code

3. Add data values

The Data for the linear meter diagram is collected from Our World in Data and included in the code. On the site, we can see the percentage of people around the world who have received one and two doses of COVID-19 vaccine on every continent.

Because no number is greater than 50% (at the time of writing), we keep the maximum limit for all linear meter axes at 50%, and we compare each continent’s distance from the marker, as well as the global number. We used leds for numbers of at least partial vaccinations and bar Pointers for numbers of full vaccinations. We’ll see how to add data in the last step.

Now that our initial steps are complete, let’s add the code to make a linear meter diagram in JavaScript!

4. Write JavaScript code for charts

Before adding any code, we wrap everything in a function to ensure that the entire code executes only after the page loads.

Creating a linear meter diagram involves several steps and is a little more complex than the other basic chart types. But that doesn’t mean it’s very difficult, and we’ll go through each step to see how the diagrams are made.

Defines the linear scale and axis of the meter diagram

We have multiple Pointers in our chart. So let’s start by creating a function that accepts two values: one for the bar pointer and one for the LED meter. We will then create a meter, set the data, and specify the layout as horizontal. Next, we will set the scale and axis range. We will make linear proportions with a minimum and maximum range. For the axis, we will define the properties and set the orientation:

function drawGauge(value, settings) {
  // Create gauge with settings
  const gauge = anychart.gauges.linear();
  gauge.data([value, settings.value]);
  gauge.layout('horizontal');

  // Set scale for gauge
  const scale = anychart.scales.linear();
  scale.minimum(0).maximum(settings.maximum).ticks({ interval: 2 });

  // Set axis for gauge
  const axis = gauge.axis(0);
  axis.width('1%').offset('43%').scale(scale).orientation('bottom');
}
Copy the code

Sets bar pointer and label

Now we will create the bar pointer and label for the bar series. Give the label an offset to avoid overlapping with the pointer:

// Create and set bar point
const barSeries = gauge.bar(0);

barSeries
  .scale(scale)
  .width('4%');

// Create and set label with actual data
const labelBar = barSeries.labels();
labelBar
  .enabled(true)
  .offsetY('-15px');
Copy the code

Create LED pointer and set color properties

In LED points, we point to the gap between the points and use the Dimmer property to set the color of the remaining LED points to indicate the effect of not being bright. We will also declare the color scale of the lit LED points:

// Create and set LED point const ledPointer = gauge.led(1); LedPointer. Offset ('10%').width('30%').count(settings.maximum).scale(scale).gap(0.55).dimmer(function () {return '#eee'; }); ledPointer.colorScale().colors(['#63b39b', '#63b39b']);Copy the code

Declare the meter with the target value for each data point

To make linear meters for each continent, we will call the functions defined above and their data for each region. The first number represents the target value data and the second variable is the object with the LED data. Maximum remains constant at 50, but instead values the percentage value of the fully vaccinated population at each data point. The value will be displayed by a pointer:

// Create a bar and gauge = drawGauge(13.68, {maximum: 50, value: 27.13}); Const Europe = drawGauge(36.98, {maximum: 50, value: 1}); Const nAmerica = drawGauge(36.77, {maximum: 50, value: 1}); Const sAmerica = drawGauge(22.8, {maximum: 50, value: 40.54}); Const Asia = drawGauge(10.14, {maximum: 50, value: 27.16}); Const Oceania = drawGauge(9.75, {maximum: 50, value: 21}); Const Africa = drawGauge(1.56, {maximum: 50, value: 1.04});Copy the code

Set up the layout of the linear meter

To display each linear meter under another, we will define a table and add the title as a separate row along with each data point. We’ll add various attributes of the layout, such as alignment and font size. We will also define parameters for the first row, since it is the header, and set the width property for the first column to 100%, since we don’t need any more columns:

// Create table to place gauges
const layoutTable = anychart.standalones.table();
layoutTable
  .hAlign('right')
  .vAlign('middle')
  .fontSize(14)
  .cellBorder(null);

// Put gauges into the layout table
layoutTable.contents([
  [null, 'Covid-19 Vaccination - How far are we from the halfway mark?'],
  ['World', world],
  ['Europe', europe],
  ['North America', nAmerica],
  ['South America', sAmerica],
  ['Asia', asia],
  ['Oceania', oceania],
  ['Africa', africa]
]);

// Set height for first row in layout table
layoutTable
  .getRow(0)
  .height(50)
  .fontSize(22)
  .hAlign('center');

// Set the first column to 100% width
layoutTable.getCol(0).width(100);
Copy the code

Draw diagrams

The last step is referencing

We added the containers in the previous step and plotted them:

// Set container id and initiate drawing
layoutTable.container('container');
layoutTable.draw();
Copy the code

That’s it. We now have a fully functional and beautiful JavaScript linear meter diagram! You can view the code for the initial version of this linear gauge on CodePen.

Make the chart accessible

It is a good practice to ensure that as many people as possible have access to the chart. So, with a11Y in mind, we made a basic version of linear meter diagrams that are more suitable for screen readers. You can view this here and read more about it in the documentation of the AnyChart JavaScript library.

Custom linear meter

The default linear meter chart we made looks great now, but a few changes will improve readability and make the chart even better. The JavaScript library is great not only for creating charts quickly, but also for customizing visualizations as needed. The chart library provides a number of configuration options for controlling chart behavior and aesthetics. Let’s make some small but effective adjustments to our current linear instrumentation diagram.

Color change

To make the linear meter look more cohesive, let’s set the color property of the bar pointer to the darker version of the LED point. We will do this by specifying the fill and stroke properties of the column:

// Create and set bar point
const barSeries = gauge.bar(0);
barSeries
  .scale(scale)
  .width('4%')
  .fill('#296953')
  .stroke('#296953');
Copy the code

Add a legend to our linear meter diagram

Since we use different colors for bar charts, lit and unlit LED Pointers, it is best to provide a legend to explain the colors. We’ll make a legend and add it below the chart title:

// Create stand alone legend
const legend = anychart.standalones.legend();
legend
.position('center')
.items([
    { text: 'Fully vaccinated', iconFill: '#296953' },
    { text: 'Partially vaccinated', iconFill: '#63b39b' },
    { text: 'Not vaccinated', iconFill: '#eee' }
]);
Copy the code

Tooltip format

To facilitate better data communication, let’s format the tooltip to make it more informative by displaying values as percentages and indicating that the maximum value of the meter is 50% :

// Set gauge tooltip
gauge
    .tooltip()
    .useHtml(true)
    .titleFormat('{%Value} %')
        .format(
        'Maximum on scale: ' +
        settings.maximum +
        ' %'
    );
Copy the code

See the full code for this release at CodePen.

Axis and label formats

The last thing we need to do is display all the data values as percentages to avoid any confusion. We will also add a subheading as a row in the table below the heading to indicate that the value is a percentage. The last thing is to beautify the bar labels with a bolder font.

The complete final code for this JavaScript linear meter diagram can be found on CodePen.

conclusion

In this step-by-step tutorial, we’ve seen that it’s not hard to create functional and visually appealing JavaScript diagrams using a good JavaScript. See documentation and examples to better understand the features and properties of linear quantities.

If this article has been helpful to you, don’t forget to give me a triple like, retweet, comment, and we’ll see you next time.

Collection is equal to white piao, praise is true feelings.

Dear friends, if you need JAVA interview documents, please click “like” and “forward”. After following me, I can get free information on 333