Configure Gauges

This guide contains detailed instructions on how to configure the dxCircularGauge, dxLinearGauge and dxBarGauge widgets. You will learn how to provide data to be visualized on a gauge and customize its appearance per your requirements. As a result, you will get the dxCircularGauge and dxLinearGauge that show the local temperature and the temperature in the selected city, and the dxBarGauge that shows the temperature in several cities at once. These gauges will display the temperature in Celsuis.

Configure a Circular Gauge

This topic provides step-by-step instructions on how to configure the dxCircularGauge widget.

Create a Circular Gauge

Begin by creating an HTML file. Then, add references to the required libraries (see the Add Libraries tutorial).

HTML
<!DOCTYPE html>
  <html>
      <head>
          <meta charset="utf-8" />
          <script type="text/javascript" src="jquery-2.0.3.min.js"></script>
          <!--script type="text/javascript" src="knockout-3.0.0.js"></script-->
          <!--script type="text/javascript" src="angular.min.js"></script-->
          <script type="text/javascript" src="globalize.min.js"></script>
          <script type="text/javascript" src="dx.chartjs.js"></script>
      </head>
      <body></body>
  </html>

There are several approaches to creating a ChartJS widget. This page will utilize the jQuery approach. Refer to the Add a Widget tutorial to go over the remaining approaches.

Add a div element. It will be a container for the dxCircularGauge widget.

HTML
<body>
    <div id="gaugeContainer" style="height:320px"></div>
</body>

Create the dxCircularGauge widget within the added container.

HTML
<head>
    <!-- ... -->
    <script type="text/javascript">
        $(function () {
            $("#gaugeContainer").dxCircularGauge({});
        })
    </script>
</head>

Run this code and you will see the gauge with the default settings. It does not look much like a thermometer yet, so we have to customize it. To begin, provide data for the gauge.

Provide Data

According to the declared task, the value indicator must show the temperature in the selected city and the subvalue indicator must show the temperature in the current city. But to start learning dxCircularGauge basics, we will simply assign random values. To set data for a gauge, specify the scale, value, subvalues and rangeContainer objects within the configuration object.

JavaScript
$("#gaugeContainer").dxCircularGauge({
    scale: {
        startValue: -50,
        endValue: 50
    },
    value: 24,
    subvalues: [19],
    rangeContainer: {
        ranges: [{
                startValue: -50,
                endValue: 0,
                color: 'blue'
            }, {
                startValue: 0,
                endValue: 50,
                color: 'red'
            }
        ]
    }  
});

As you can see in this code, the scale boundaries are set using startValue and endValue options. Gauge values are assigned to the value and subvalues fields. The rangeContaner object defines two ranges - their start/end values and color.

Scale Adjustment

A scale is displayed by major and minor ticks, as well as labels. As you can see in the previous step's result, we can leave the labels as they are. But we need to change the way major ticks are displayed and the way they visualize minor ticks (as they are not shown by default).

JavaScript
$("#gaugeContainer").dxCircularGauge({
    //...
    scale: {
        //...
        majorTick: {
            color: 'black',
            tickInterval: 10
        },
        minorTick: {
            visible: true,
            color: 'black',
            tickInterval: 1
        }
    }
});

In the code above, we have made minor ticks visible, and colored both the major and minor ticks in black. In addition, we have specified tick intervals for those ticks.

So that the range container does not overlap the scale, it should be shifted toward the center of the gauge. Move to the next step to learn how to do this.

Ranges Adjustment

Offset the ranges, so that they do not overlap the scale. In the dxCircularGauge widget, the position of any element is specified by an offset from an invisible scale line. The offset of ranges is set to 0 by default. To set the required offset for ranges, use the offset option of the rangeContainer object.

JavaScript
$("#gaugeContainer").dxCircularGauge({
    //...
    rangeContainer: {
        //...
        offset: 5,
    },
});

In the code above, 5 is the offset of the range container relative to its previous position.

Value Indicator Adjustment

To implement the current task, change the color of the value indicator and reduce the diameter of the spindle gap. You can change the appearance of the value indicator using the valueIndicator configuration object.

JavaScript
$("#gaugeContainer").dxCircularGauge({
      //...
      valueIndicator: {
          //...
          color : 'red',
          spindleGapSize: 5
      }
  });

Subvalue Indicator Adjustment

The last thing that is left to change in the circular gauge is the color of the subvalue indicator. To specify it, use the color option of the subvalueIndicator configuration object.

JavaScript
$("#gaugeContainer").dxCircularGauge({
    //...
    subvalueIndicator: {
        //...
        color: 'green'
    }
});

Runtime Data Update

To complete the implementation of the application, the dxCircularGauge widget should be updated when the user selects a city from the list.

First, add a combobox that will allow you to select a city, then paste the following code in the HTML file.

HTML
<select id="citySelector">
    <option value="44418">London</option>
    <option value="638242">Berlin</option>
    <option value="2459115">New York</option>
    <option value="24553382">Moscow</option>
    <option value="1225448">Bangkok</option>
</select>

As you can see in the code above, each city is identified by a unique WOEID. The next step is to update the main gauge value when a city is changed. The temperature in the selected city will be requested from the Yahoo! Weather Web service using the Yahoo! Query Language (YQL). To perform a query, use the ajax() jQuery function.

Next, handle the combobox's change event. To update the main gauge value, get the dxCircularGauge instance and call its value method with a new value passed as the parameter.

JavaScript
$('#citySelector').change(function () {
    var cityCode = this.value,
        gauge = $('#gaugeContainer').dxCircularGauge('instance'),
        query = 'select item.condition.temp from weather.forecast where woeid="' + cityCode + '" and u="c"',
        url = "http://query.yahooapis.com/v1/public/yql?format=json&q=" + escape(query);

    $.ajax(url, { dataType: 'jsonp' }).done(function (data) {
        var forecast = data.query.results;
        if (forecast) {
            gauge.value(parseFloat(forecast.channel.item.condition.temp));
        }
    });
});

Run the complete code and check that the value indicator is set to the temperature that is specified for the currently selected city.

Configure a Linear Gauge

Along with the dxCircularGauge widget, the ChartJS library supplies you with its line-shaped brother - the dxLinearGauge widget. Use this topic to learn how to configure this widget to your requirements, and thus get a linear gauge that displays the local temperature and the temperature of the selected city.

Like all widgets from the ChartJS library, the dxLinearGauge widget can be created using the jQuery, Knockout or AngularJS approach. All of these approaches are detailed in the Add a Widget tutorial.

To provide data for the dxLinearGauge, define the scale, value, subvalues and rangeContainer objects, as you did for the dxCircularGague widget in the previous steps.

HTML
<div id="linearGaugeContainer" style="height:30px"></div>
JavaScript
$("#linearGaugeContainer").dxLinearGauge({
    scale: {
        startValue: -50,
        endValue: 50,
    },
    value: 24,
    subvalues: [19],
    rangeContainer: {
        ranges: [{
                startValue: -50,
                endValue: 0,
                color: 'blue'
            }, {
                startValue: 0,
                endValue: 50,
                color: 'red'
            }
        ]
    }
});

Now, add minor ticks, as you did for the circular gauge.

JavaScript
$("#linearGaugeContainer").dxLinearGauge({
    scale: {
        //...
        minorTick: {
            visible: true,
            tickInterval: 1
        }
    },
    //...
});

Finally, customize the colors, change the gauge's orientation, and shift the range container and value and subvalue indicators so that they do not overlap each other. The following code demonstrates this.

JavaScript
$("#linearGaugeContainer").dxLinearGauge({
    geometry: {
        orientation: 'vertical'
    },
    scale: {
        //...
        majorTick: {
            color: 'black',
        }
        minorTick: {
            //...
            color: 'black'
        }
    },
    value: 24,
    valueIndicator: { color: 'red', offset: 10 },
    subvalues: [19],
    subvalueIndicator: { color: 'green', offset: -5 },
    rangeContainer: {
        //...
        offset: -5
    }
    //...
});

As you can see, the dxLinearGauge and dxCircularGauge widgets have much in common. The only difference is the shape of the scale.

Add a combobox and handle its change event just like you did for the dxCircularGauge widget above.

Configure a Bar Gauge

The dxBarGauge widget is configured similarly to other gauge widgets, though it has several distinctive features that should be emphasized. According to our task, dxBarGauge should display temperature in several cities at once. This topic will guide you through configuring the dxBarGauge widget to implement this task.

Create a Bar Gauge

Actions described in this subtopic replicate the actions that have already been performed when creating a dxCircularGauge.

Begin by creating an HTML file. Then, add references to the required libraries (see the Add Libraries tutorial).

Like all the widgets from the ChartJS library, the dxBarGauge widget can be created using the jQuery, Knockout or AngularJS approach. All of these approaches are detailed in the Add a Widget tutorial. On this page, the jQuery approach is used.

Add a div container and create the dxBarGauge widget within it.

HTML
<body>
    <div id="barGaugeContainer" style="height:320px"></div>
</body>
HTML
<head>
    <!-- ... -->
    <script type="text/javascript">
        $(function () {
            $("#barGaugeContainer").dxBarGauge({});
        })
    </script>
</head>

Run this code and you will see an empty gauge. In the next step, we will populate it with data.

Provide Data

According to the declared task, the bars on the dxBarGauge should indicate the temperature in several cities. But to start learning dxBarGauge basics, we will simply assign random values. First, determine the range of values to be indicated on the gauge. For this purpose, use the startValue and endValue options. Next, set data for the gauge using the values option. This option accepts an array of values to be indicated on a gauge.

JavaScript
$("#barGaugeContainer").dxBarGauge({
    startValue: -50,
    endValue: 50,
    values: [9, 2, 3, -9, 27]
});

If you run this code, you will see a gauge displaying the specified values. But these values do not represent actual data. It is time to add a slightly more advanced feature to our gauge - the capability to receive real data from a server and update the gauge values on document ready. The following code demonstates how to handle this event using the .ready() jQuery function.

JavaScript
$(document).ready(function () {
    // ...
});

Our gauge will display the temperature in the same cities that are available in the applications previously implemented with the dxCircularGauge and dxLinearGauge widgets. Since we now need multiple temperature values, we should make several queries to the server.

JavaScript
$(document).ready(function () {
    var cityCodes = [44418, 638242, 2459115, 24553382, 1225448],
        urls = [], query;

    cityCodes.forEach(function (cityCode) {
        query = 'select item.condition.temp from weather.forecast where woeid="' + cityCode + '" and u="c"';
        url = "http://query.yahooapis.com/v1/public/yql?format=json&q=" + escape(query);
        urls.push(url);
    });

    // ...
});

As you can see in the code above, each city is identified by a unique WOEID. The temperature in these cities is requested from the Yahoo! Weather Web service using the Yahoo! Query Language (YQL). One query is performed using the ajax() jQuery function. But in our case, we need to perform several consecutive queries. Use the when() jQuery function to do this.

JavaScript
$(document).ready(function () {
    // ...

    var barGauge = $('#barGaugeContainer').dxBarGauge('instance'),
        temperatures = [];

    var retrieveData = function () {
        for (var i = 0; i < arguments.length; i++) {
            temperatures.push(parseFloat(arguments[i][0].query.results.channel.item.condition.temp));
        };
        barGauge.values(temperatures);
    };

    $.when($.ajax(urls[0]), $.ajax(urls[1]), $.ajax(urls[2]), $.ajax(urls[3]), $.ajax(urls[4])).then(retrieveData);
});

In the code above, the retrieveData function is called after all the queries are completed. This function pushes the received values into an array of temperatures and passes this array to the values(newValues) method of the dxBarGauge instance.

Run this code now and you will see that the gauge displays real values obtained from the Yahoo! Weather Web service. Since the technical part of configuring the dxBarGauge widget is complete, it is now time to customize its appearance.

Customize the Appearance

In this section, we will adjust the appearance of the dxBarGauge widget. Set the appropriate format for labels and customize their text using the format and customizeText options of the label object. In addition, change the default palette to another predefined palette using the palette option, as demonstrated in the code below.

JavaScript
$("#barGaugeContainer").dxBarGauge({
    // ...

    label: {
        format: 'decimal',
        customizeText: function () {
            return this.valueText + '&deg;C'
        }
    },
    palette: 'Bright'
});

Your gauge is now almost ready to use, but it has one inconvenient feature - we cannot identify cities on the gauge. Enabling tooltips will fix this issue. Move to the final step to learn how to do this.

Enable Tooltips

A tooltip is a small pop-up rectangle that displays the value of the bar that is currently hovered over. By default, tooltips are disabled. To enable them, assign true to the enabled option of the tooltip configuration object. Along with the temperature, a tooltip should display the city corresponding to this temperature. Use the customizeText option to customize the tooltip's text. A city can be identified by the corresponding index in the array of gauge values.

JavaScript
$("#barGaugeContainer").dxBarGauge({
    // ...
    tooltip: {
        enabled: true,
        format: 'decimal',
        customizeText: function () {
            var cityName;
            switch (this.index) {
                case 0: cityName = 'London'
                    break;
                case 1: cityName = 'Berlin'
                    break;
                case 2: cityName = 'New York'
                    break;
                case 3: cityName = 'Moscow'
                    break;
                case 4: cityName = 'Bangkok'
                    break;
                default: cityName = undefined
                    break;
            }
            return cityName + ': ' + this.valueText + '&deg;C';
        }
    }
});

Now, when you hover over a bar, the tooltip displays the name of the city corresponding to the hovered bar, as well as the temperature in this city.

This tutorial guided you through the configuration of the ChartJS gauge widgets. The full code can be found on jsFiddle. For a full list of options for each widget, see the corresponding Reference sections (dxCircularGauge, dxLinearGauge and dxBarGauge).