Skip to content

Instantly share code, notes, and snippets.

@tomerd
Last active August 6, 2022 11:53
Show Gist options
  • Save tomerd/1499279 to your computer and use it in GitHub Desktop.
Save tomerd/1499279 to your computer and use it in GitHub Desktop.
google style gauges using javascript d3.js
this is my go at recreating google's guage using d3.js.
google's version can be found at http://code.google.com/apis/chart/interactive/docs/gallery/gauge.html
function Gauge(placeholderName, configuration)
{
this.placeholderName = placeholderName;
var self = this; // for internal d3 functions
this.configure = function(configuration)
{
this.config = configuration;
this.config.size = this.config.size * 0.9;
this.config.raduis = this.config.size * 0.97 / 2;
this.config.cx = this.config.size / 2;
this.config.cy = this.config.size / 2;
this.config.min = undefined != configuration.min ? configuration.min : 0;
this.config.max = undefined != configuration.max ? configuration.max : 100;
this.config.range = this.config.max - this.config.min;
this.config.majorTicks = configuration.majorTicks || 5;
this.config.minorTicks = configuration.minorTicks || 2;
this.config.greenColor = configuration.greenColor || "#109618";
this.config.yellowColor = configuration.yellowColor || "#FF9900";
this.config.redColor = configuration.redColor || "#DC3912";
this.config.transitionDuration = configuration.transitionDuration || 500;
}
this.render = function()
{
this.body = d3.select("#" + this.placeholderName)
.append("svg:svg")
.attr("class", "gauge")
.attr("width", this.config.size)
.attr("height", this.config.size);
this.body.append("svg:circle")
.attr("cx", this.config.cx)
.attr("cy", this.config.cy)
.attr("r", this.config.raduis)
.style("fill", "#ccc")
.style("stroke", "#000")
.style("stroke-width", "0.5px");
this.body.append("svg:circle")
.attr("cx", this.config.cx)
.attr("cy", this.config.cy)
.attr("r", 0.9 * this.config.raduis)
.style("fill", "#fff")
.style("stroke", "#e0e0e0")
.style("stroke-width", "2px");
for (var index in this.config.greenZones)
{
this.drawBand(this.config.greenZones[index].from, this.config.greenZones[index].to, self.config.greenColor);
}
for (var index in this.config.yellowZones)
{
this.drawBand(this.config.yellowZones[index].from, this.config.yellowZones[index].to, self.config.yellowColor);
}
for (var index in this.config.redZones)
{
this.drawBand(this.config.redZones[index].from, this.config.redZones[index].to, self.config.redColor);
}
if (undefined != this.config.label)
{
var fontSize = Math.round(this.config.size / 9);
this.body.append("svg:text")
.attr("x", this.config.cx)
.attr("y", this.config.cy / 2 + fontSize / 2)
.attr("dy", fontSize / 2)
.attr("text-anchor", "middle")
.text(this.config.label)
.style("font-size", fontSize + "px")
.style("fill", "#333")
.style("stroke-width", "0px");
}
var fontSize = Math.round(this.config.size / 16);
var majorDelta = this.config.range / (this.config.majorTicks - 1);
for (var major = this.config.min; major <= this.config.max; major += majorDelta)
{
var minorDelta = majorDelta / this.config.minorTicks;
for (var minor = major + minorDelta; minor < Math.min(major + majorDelta, this.config.max); minor += minorDelta)
{
var point1 = this.valueToPoint(minor, 0.75);
var point2 = this.valueToPoint(minor, 0.85);
this.body.append("svg:line")
.attr("x1", point1.x)
.attr("y1", point1.y)
.attr("x2", point2.x)
.attr("y2", point2.y)
.style("stroke", "#666")
.style("stroke-width", "1px");
}
var point1 = this.valueToPoint(major, 0.7);
var point2 = this.valueToPoint(major, 0.85);
this.body.append("svg:line")
.attr("x1", point1.x)
.attr("y1", point1.y)
.attr("x2", point2.x)
.attr("y2", point2.y)
.style("stroke", "#333")
.style("stroke-width", "2px");
if (major == this.config.min || major == this.config.max)
{
var point = this.valueToPoint(major, 0.63);
this.body.append("svg:text")
.attr("x", point.x)
.attr("y", point.y)
.attr("dy", fontSize / 3)
.attr("text-anchor", major == this.config.min ? "start" : "end")
.text(major)
.style("font-size", fontSize + "px")
.style("fill", "#333")
.style("stroke-width", "0px");
}
}
var pointerContainer = this.body.append("svg:g").attr("class", "pointerContainer");
var midValue = (this.config.min + this.config.max) / 2;
var pointerPath = this.buildPointerPath(midValue);
var pointerLine = d3.svg.line()
.x(function(d) { return d.x })
.y(function(d) { return d.y })
.interpolate("basis");
pointerContainer.selectAll("path")
.data([pointerPath])
.enter()
.append("svg:path")
.attr("d", pointerLine)
.style("fill", "#dc3912")
.style("stroke", "#c63310")
.style("fill-opacity", 0.7)
pointerContainer.append("svg:circle")
.attr("cx", this.config.cx)
.attr("cy", this.config.cy)
.attr("r", 0.12 * this.config.raduis)
.style("fill", "#4684EE")
.style("stroke", "#666")
.style("opacity", 1);
var fontSize = Math.round(this.config.size / 10);
pointerContainer.selectAll("text")
.data([midValue])
.enter()
.append("svg:text")
.attr("x", this.config.cx)
.attr("y", this.config.size - this.config.cy / 4 - fontSize)
.attr("dy", fontSize / 2)
.attr("text-anchor", "middle")
.style("font-size", fontSize + "px")
.style("fill", "#000")
.style("stroke-width", "0px");
this.redraw(this.config.min, 0);
}
this.buildPointerPath = function(value)
{
var delta = this.config.range / 13;
var head = valueToPoint(value, 0.85);
var head1 = valueToPoint(value - delta, 0.12);
var head2 = valueToPoint(value + delta, 0.12);
var tailValue = value - (this.config.range * (1/(270/360)) / 2);
var tail = valueToPoint(tailValue, 0.28);
var tail1 = valueToPoint(tailValue - delta, 0.12);
var tail2 = valueToPoint(tailValue + delta, 0.12);
return [head, head1, tail2, tail, tail1, head2, head];
function valueToPoint(value, factor)
{
var point = self.valueToPoint(value, factor);
point.x -= self.config.cx;
point.y -= self.config.cy;
return point;
}
}
this.drawBand = function(start, end, color)
{
if (0 >= end - start) return;
this.body.append("svg:path")
.style("fill", color)
.attr("d", d3.svg.arc()
.startAngle(this.valueToRadians(start))
.endAngle(this.valueToRadians(end))
.innerRadius(0.65 * this.config.raduis)
.outerRadius(0.85 * this.config.raduis))
.attr("transform", function() { return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(270)" });
}
this.redraw = function(value, transitionDuration)
{
var pointerContainer = this.body.select(".pointerContainer");
pointerContainer.selectAll("text").text(Math.round(value));
var pointer = pointerContainer.selectAll("path");
pointer.transition()
.duration(undefined != transitionDuration ? transitionDuration : this.config.transitionDuration)
//.delay(0)
//.ease("linear")
//.attr("transform", function(d)
.attrTween("transform", function()
{
var pointerValue = value;
if (value > self.config.max) pointerValue = self.config.max + 0.02*self.config.range;
else if (value < self.config.min) pointerValue = self.config.min - 0.02*self.config.range;
var targetRotation = (self.valueToDegrees(pointerValue) - 90);
var currentRotation = self._currentRotation || targetRotation;
self._currentRotation = targetRotation;
return function(step)
{
var rotation = currentRotation + (targetRotation-currentRotation)*step;
return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(" + rotation + ")";
}
});
}
this.valueToDegrees = function(value)
{
// thanks @closealert
//return value / this.config.range * 270 - 45;
return value / this.config.range * 270 - (this.config.min / this.config.range * 270 + 45);
}
this.valueToRadians = function(value)
{
return this.valueToDegrees(value) * Math.PI / 180;
}
this.valueToPoint = function(value, factor)
{
return { x: this.config.cx - this.config.raduis * factor * Math.cos(this.valueToRadians(value)),
y: this.config.cy - this.config.raduis * factor * Math.sin(this.valueToRadians(value)) };
}
// initialization
this.configure(configuration);
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>d3.js gauges</title>
<style>
body
{
font: 10px arial;
}
</style>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<script type="text/javascript" src="gauge.js"></script>
<script>
var gauges = [];
function createGauge(name, label, min, max)
{
var config =
{
size: 120,
label: label,
min: undefined != min ? min : 0,
max: undefined != max ? max : 100,
minorTicks: 5
}
var range = config.max - config.min;
config.yellowZones = [{ from: config.min + range*0.75, to: config.min + range*0.9 }];
config.redZones = [{ from: config.min + range*0.9, to: config.max }];
gauges[name] = new Gauge(name + "GaugeContainer", config);
gauges[name].render();
}
function createGauges()
{
createGauge("memory", "Memory");
createGauge("cpu", "CPU");
createGauge("network", "Network");
//createGauge("test", "Test", -50, 50 );
}
function updateGauges()
{
for (var key in gauges)
{
var value = getRandomValue(gauges[key])
gauges[key].redraw(value);
}
}
function getRandomValue(gauge)
{
var overflow = 0; //10;
return gauge.config.min - overflow + (gauge.config.max - gauge.config.min + overflow*2) * Math.random();
}
function initialize()
{
createGauges();
setInterval(updateGauges, 5000);
}
</script>
</head>
<body onload="initialize()">
<span id="memoryGaugeContainer"></span>
<span id="cpuGaugeContainer"></span>
<span id="networkGaugeContainer"></span>
<span id="testGaugeContainer"></span>
</body>
</html>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
@jondot
Copy link

jondot commented Jan 26, 2012

Looks great. Nicely done!

@rubenfilteris
Copy link

Would you mind if I use these in a commercial project?
Regards
Ruben

@tomerd
Copy link
Author

tomerd commented Jul 9, 2012 via email

@viswesh
Copy link

viswesh commented Nov 13, 2012

This is good stuff Tomer! For gauges[key].redraw(80) i.e, when 80 is passed, the SVG pointer animates (.ease("linear")) anti clock wise from 0 to 80. How could we modify the pointer path so that it always takes clock wise as direction? Thanks!

@closealert
Copy link

Small suggestion for negative minimum values:

    this.valueToDegrees = function(value)
    {
        return value / this.config.range * 270 - (this.config.min/this.config.range*270+45);
    }

@robotfuel
Copy link

What is the license on this? I'd like to use it on a commercial website

@tomerd
Copy link
Author

tomerd commented Jun 1, 2013

@robotfuel no special license. feel free to use it however you like.

@AbhishekGhosh
Copy link

Excellent work.

@mr23
Copy link

mr23 commented Jul 13, 2013

A while back I popped this into a JSFiddle, then added some additional functionality, finally wrapping into a Dashboard with a (simple) day/night switch. See notes below on most changes. Since I did this a few months back it won't have any subsequent updates by TD incorporated.

http://jsfiddle.net/mr23/vJuNU/

Since JSFiddle is sometimes a little slow to load you might want to first look at the result at
http://jsfiddle.net/mr23/vJuNU/embedded/result/

Thanks for a fun mini-project to learn a few new things (D3, JS, JSFiddle).

As Tomer Doron said, my JSFiddle contents can be used as desired.

// Rev 0.1: Added Dim selector, and refactored gauge's 'face' into components
// and sw methods to allow changing color, added a 'size bias' for the gauge
// size, to allow having some larger than others, and added an interval var
// allowing an 'initialization' interval and a 'runtime' interval. If interval
// updates faster than 200ms, it can cause the gauge pointer to distort. This
// occurs because the line control's 'transition' isn't written to follow a
// gauge's circular rotation, it simply is a line transition and is allowed to
// shorten/lengthen. This can be seen after the 'powerup' sweep, when the
// 'readings' are set to 50 as a starting point.
// Author is learning D3, SVG, Javascript, JSFiddle etc.

@tomerd
Copy link
Author

tomerd commented Jul 16, 2013

updated with several bug fixes, including negative values (thanks @closealert) pointer animation effect and others

@rkprabakar
Copy link

I want it as 180 degree of this gauge...How to convert this js to display as 180 instead of 360?

@brickta
Copy link

brickta commented Aug 30, 2013

Tomer, thank you for this great work. I had need for an offline gauge and this works great. One question, I would like to dynamically change the configuration (max and subsequent color bands) of a rendered gauge based on a selected data source. Do you know how this can be done? I've tired $("myid").empty() in the

container for the gauge and re-rendering, but I end up with new gauges in addition to the old one. My application is a web page that displays the current of selected circuits, which can be modified. I'm not well versed in d3, but can usually do JS and jQ okay. Thank you for your help. Todd

@thlorenz
Copy link

Just letting you know, I used your implementation as the starting point for a d3-gauge module.

Most of the ideas came from your post.
I restructured the code and made it fully configurable and style-able so you can use it in lots of situations.

@LouisGi
Copy link

LouisGi commented May 15, 2014

Tom, is it possible to have multiple indicators (needles) on each gauge?

@pluger
Copy link

pluger commented Aug 9, 2015

Hi tomerd, i modificated the code for real time update form mysql an php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
        <title></title>

        <script type="text/javascript" src="js/d3.v2.js"></script>
                <script type="text/javascript" src="js/jquery-1.10.2.js" ></script>
        <script type="text/javascript" src="js/gauge.js"></script>

        <script>



            var gauges = [];

            function createGauge(name, label, min, max)
            {
                var config = 
                {
                    size: 200,
                    label: label,
                    min: undefined != min ? min : 0,
                    max: undefined != max ? max : 1000,
                    minorTicks: 5
                }

                var range = config.max - config.min;
                config.yellowZones = [{ from: config.min + range*0.75, to: config.min + range*0.9 }];
                config.redZones = [{ from: config.min + range*0.9, to: config.max }];

                gauges[name] = new Gauge(name, config);
                gauges[name].render();
            }

            function createGauges()
            {
                createGauge("a01", "a01");

            }

            function updateGauges_old()
            {
                for (var key in gauges)
                {
                    var value = getActualValue(gauges[key])
                    gauges[key].redraw(value);
                }
            }


                        function updateGauges () {$.ajax({
                            url:'php/gaugesca01.php',
                            type:'GET',
                            dataType:'json',
                                data:{}}).done(function(newValue)
                                {                                        
                                    for (var key in gauges)
                                    {
                                            gauges[key].redraw(newValue);
                                    }
                                });
                        }                        


            function initialize()
            {
                createGauges();
                setInterval(updateGauges, 500);
            }

        </script>


    </head>

    <body onload="initialize()">
        <span id="a01"></span>

    </body>

</html>

the php code

<?php
include ("config.php");
$mysqli = new mysqli($db_server, $db_user, $db_pass, $db_name );

if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }
$result = $mysqli->query("SELECT a01 from table order by id desc limit 1");


foreach($result as $r) {

    if ($result != null)
    {
       $rows = array('a01' => (float) $r['a01']);
       echo $r['a01'];
    }

        if ($result == null)
    {
       $rows = array('0' => (float) '0');
    }

}

?>

@paulinm
Copy link

paulinm commented Jan 12, 2016

Hi tomerd, love the gauge. It was almost exactly what I needed. I modified the code slightly to allow for tracking of min, running average, and max values on the gauge with labeled markers as well as stationary values under the "current" value. I also added labels for all of them and moved all of the user-configurable styling (i.e. background colors, font colors, opacity, etc.) to CSS while leaving other styling, mostly regarding scaling and positioning, "closed off" inside of gauge.js. Thanks again.

screen

@bnest
Copy link

bnest commented Feb 11, 2016

@paulinm
Can you maybe upload your code as well?

@JIeH9Iu
Copy link

JIeH9Iu commented Apr 14, 2016

Hello. Good example. Can you add a second arrow on the gauge?

@JIeH9Iu
Copy link

JIeH9Iu commented Apr 17, 2016

Here is my code for two hands. File gauge.js. And metod "gauges[key].redraw(value,value1);" called with two values.
Maybe he's not quite true, but it works.

function Gauge(placeholderName, configuration)
{
this.placeholderName = placeholderName;

var self = this; // for internal d3 functions

this.configure = function(configuration)
{
    this.config = configuration;

    this.config.size = this.config.size * 0.9;

    this.config.raduis = this.config.size * 0.97 / 2;
    this.config.cx = this.config.size / 2;
    this.config.cy = this.config.size / 2;

    this.config.min = undefined != configuration.min ? configuration.min : 0; 
    this.config.max = undefined != configuration.max ? configuration.max : 100; 
    this.config.range = this.config.max - this.config.min;

    this.config.majorTicks = configuration.majorTicks || 5;
    this.config.minorTicks = configuration.minorTicks || 2;

    this.config.greenColor  = configuration.greenColor || "#FFFFFF";
    this.config.yellowColor = configuration.yellowColor || "#FFFFFF";
    this.config.redColor    = configuration.redColor || "#FFFFFF";

    this.config.transitionDuration = configuration.transitionDuration || 500;
}

this.render = function()
{
    this.body = d3.select("#" + this.placeholderName)
        .append("svg:svg")
        .attr("class", "gauge")
        .attr("width", this.config.size)
        .attr("height", this.config.size);

    this.body.append("svg:circle")
        .attr("cx", this.config.cx)
        .attr("cy", this.config.cy)
        .attr("r", this.config.raduis)
        .style("fill", "#ccc")
        .style("stroke", "#000")
        .style("stroke-width", "0.5px");

    this.body.append("svg:circle")
        .attr("cx", this.config.cx)
        .attr("cy", this.config.cy)
        .attr("r", 0.9 * this.config.raduis)
        .style("fill", "#fff")
        .style("stroke", "#e0e0e0")
        .style("stroke-width", "2px");

    for (var index in this.config.greenZones)
    {
        this.drawBand(this.config.greenZones[index].from, this.config.greenZones[index].to, self.config.greenColor);
    }

    for (var index in this.config.yellowZones)
    {
        this.drawBand(this.config.yellowZones[index].from, this.config.yellowZones[index].to, self.config.yellowColor);
    }

    for (var index in this.config.redZones)
    {
        this.drawBand(this.config.redZones[index].from, this.config.redZones[index].to, self.config.redColor);
    }

    if (undefined != this.config.label)
    {
        var fontSize = Math.round(this.config.size / 9);
        this.body.append("svg:text")
            .attr("x", this.config.cx)
            .attr("y", this.config.cy / 2 + fontSize / 2)
            .attr("dy", fontSize / 2)
            .attr("text-anchor", "middle")
            .text(this.config.label)
            .style("font-size", fontSize + "px")
            .style("fill", "#333")
            .style("stroke-width", "0px");
    }

    var fontSize = Math.round(this.config.size / 16);
    var majorDelta = this.config.range / (this.config.majorTicks - 1);
    for (var major = this.config.min; major <= this.config.max; major += majorDelta)
    {
        var minorDelta = majorDelta / this.config.minorTicks;
        for (var minor = major + minorDelta; minor < Math.min(major + majorDelta, this.config.max); minor += minorDelta)
        {
            var point1 = this.valueToPoint(minor, 0.75);
            var point2 = this.valueToPoint(minor, 0.85);

            this.body.append("svg:line")
                .attr("x1", point1.x)
                .attr("y1", point1.y)
                .attr("x2", point2.x)
                .attr("y2", point2.y)
                .style("stroke", "#666")
                .style("stroke-width", "1px");
        }

        var point1 = this.valueToPoint(major, 0.7);
        var point2 = this.valueToPoint(major, 0.85);    

        this.body.append("svg:line")
            .attr("x1", point1.x)
            .attr("y1", point1.y)
            .attr("x2", point2.x)
            .attr("y2", point2.y)
            .style("stroke", "#333")
            .style("stroke-width", "2px");

        if (/*major == this.config.min || major == this.config.max*/true)
        {
            var point = this.valueToPoint(major, 0.63);

            this.body.append("svg:text")
                .attr("x", point.x)
                .attr("y", point.y)
                .attr("dy", fontSize / 3)
                //.attr("text-anchor", major == this.config.min ? "start" : "end")
                .attr("text-anchor", "middle")
                .text(major)
                .style("font-size", fontSize + "px")
                .style("fill", "#333")
                .style("stroke-width", "0px");
        }
        /*
        //-max   +max
         if (major == 0)
         {
         var point = this.valueToPoint(major, 0.63);

         this.body.append("svg:text")
         .attr("x", point.x)
         .attr("y", point.y)
         .attr("dy", fontSize / 3)
         .attr("text-anchor", "middle")
         .text(major)
         .style("font-size", fontSize + "px")
         .style("fill", "#333")
         .style("stroke-width", "0px");
         }*/
    }

    var pointerContainer = this.body.append("svg:g").attr("class", "pointerContainer");

    var midValue = (this.config.min + this.config.max) / 2;

    var pointerPath = this.buildPointerPath(midValue);

    var pointerLine = d3.svg.line()
                                .x(function(d) { return d.x })
                                .y(function(d) { return d.y })
                                .interpolate("basis");

    pointerContainer.selectAll("path")
                        .data([pointerPath])
                        .enter()
                            .append("svg:path")
                                .attr("d", pointerLine)
                                .attr("class",'first')
                                .style("fill", "rgb(55, 192, 61)")
                                .style("stroke", "rgb(84, 106, 132)")
                                .style("fill-opacity", 0.7);

    pointerContainer.selectAll("path1")
                        .data([pointerPath])
                        .enter()
                            .append("svg:path")
                                .attr("d", pointerLine)
                                .attr("class",'second')
                                .style("fill", "#dc3912")
                                .style("stroke", "#c63310")
                                .style("fill-opacity", 0.7);
    {
        pointerContainer.append("svg:circle")
            .attr("cx", this.config.cx)
            .attr("cy", this.config.cy)
            .attr("r", 0.12 * this.config.raduis)
            .style("fill", "#4684EE")
            .style("stroke", "#666")
            .style("opacity", 1);

        var fontSize = Math.round(this.config.size / 10);
        pointerContainer.selectAll("text")
            .data([midValue])
            .enter()
            .append("svg:text")
            .attr("x", this.config.cx)
            .attr("y", this.config.size - this.config.cy / 4 - fontSize)
            .attr("dy", fontSize / 2)
            .attr("text-anchor", "middle")
            .style("font-size", fontSize + "px")
            .style("fill", "#000")
            .style("stroke-width", "0px");

        this.redraw(this.config.min, this.config.min, 0);
    }
}

this.buildPointerPath = function(value)
{
    var delta = this.config.range / 13;

    var head = valueToPoint(value, 0.85);
    var head1 = valueToPoint(value - delta, 0.12);
    var head2 = valueToPoint(value + delta, 0.12);

    var tailValue = value - (this.config.range * (1/(270/360)) / 2);
    var tail = valueToPoint(tailValue, 0.28);
    var tail1 = valueToPoint(tailValue - delta, 0.12);
    var tail2 = valueToPoint(tailValue + delta, 0.12);

    return [head, head1, tail2, tail, tail1, head2, head];

    function valueToPoint(value, factor)
    {
        var point = self.valueToPoint(value, factor);
        point.x -= self.config.cx;
        point.y -= self.config.cy;
        return point;
    }
}

this.drawBand = function(start, end, color)
{
    if (0 >= end - start) return;

    this.body.append("svg:path")
                .style("fill", color)
                .attr("d", d3.svg.arc()
                    .startAngle(this.valueToRadians(start))
                    .endAngle(this.valueToRadians(end))
                    .innerRadius(0.65 * this.config.raduis)
                    .outerRadius(0.85 * this.config.raduis))
                .attr("transform", function() { return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(270)" });
}

this.redraw = function(value, value1, transitionDuration)
{
    var pointerContainer = this.body.select(".pointerContainer");
    console.log(this.body.select(".pointerContainer").select(".first"));
    pointerContainer.selectAll("text").text(Math.round(value));

    var pointer = pointerContainer.select(".first");
    pointer.transition()
    .duration(undefined != transitionDuration ? transitionDuration : this.config.transitionDuration)
    //.delay(0)
    //.ease("linear")
    //.attr("transform", function(d)
    .attrTween("transform", function()
    {
        var pointerValue = value;
        console.log("pointerValue:"+pointerValue);
        if (value > self.config.max) pointerValue = self.config.max + 0.02*self.config.range;
        else if (value < self.config.min) pointerValue = self.config.min - 0.02*self.config.range;
        var targetRotation = (self.valueToDegrees(pointerValue) - 90);
        var currentRotation = self._currentRotation || targetRotation;
        self._currentRotation = targetRotation;

        return function(step)
        {
            var rotation = currentRotation + (targetRotation-currentRotation)*step;
            return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(" + rotation + ")";
        }
    });

    console.log(this.body.select(".pointerContainer").select(".second"));
    var pointer1 = pointerContainer.select(".second");
    pointer1.transition()
        .duration(undefined != transitionDuration ? transitionDuration : this.config.transitionDuration)
        //.delay(0)
        //.ease("linear")
        //.attr("transform", function(d)
        .attrTween("transform", function()
        {
            var pointerValue1 = value1;
            console.log("pointerValue1:"+pointerValue1);
            if (value1 > self.config.max) pointerValue1 = self.config.max + 0.02*self.config.range;
            else if (value1 < self.config.min) pointerValue1 = self.config.min - 0.02*self.config.range;
            var targetRotation1 = (self.valueToDegrees(pointerValue1) - 90);
            var currentRotation1 = self._currentRotation1 || targetRotation1;
            self._currentRotation1 = targetRotation1;

            return function(step)
            {
                var rotation1 = currentRotation1 + (targetRotation1-currentRotation1)*step;
                return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(" + rotation1 + ")";
            }
        });
}

this.valueToDegrees = function(value)
{
    // thanks @closealert
    //return value / this.config.range * 270 - 45;
    return value / this.config.range * 270 - (this.config.min / this.config.range * 270 + 45);
}

this.valueToRadians = function(value)
{
    return this.valueToDegrees(value) * Math.PI / 180;
}

this.valueToPoint = function(value, factor)
{
    return {    x: this.config.cx - this.config.raduis * factor * Math.cos(this.valueToRadians(value)),
                y: this.config.cy - this.config.raduis * factor * Math.sin(this.valueToRadians(value))      };
}

// initialization
this.configure(configuration);  

};

@kassammo
Copy link

kassammo commented Jul 5, 2016

Hello Tomerd,
is this real time , because I don't see the same results by looking with htop ?

@paulinm
Copy link

paulinm commented Jul 8, 2016

@bwestpha Sorry about the delay, I haven't been able to contribute in an unfortunate amount of time. Anyway, if you're still interested, my version, along with example styles, can be found here: https://gist.github.com/paulinm/10556397 . Thanks, Paulinm

@theWhiteFox
Copy link

theWhiteFox commented Jul 26, 2016

Hi there,
I am brand new to D3.js and I am trying to create a live data gauge. I am using this excellent example, and I have it running locally. However I would like to have each of the gauges show different live data.
So if I want to change the memory gauge do I change the updateGauges function else to select #memoryGaugeContainer?
Any help would be much appreciated.

function` updateGauges() {
        if (i >= 0) { // initially use a faster interval and sweep the gauge
            {
                for (var key in gauges) {
                    gauges[key].redraw(i);
                }
                if (i === 0) {
                    clearInterval(interv0);
                    interv0 = setInterval(updateGauges, 75);
                }
                i = i + 5;
                if (i > 100) {
                    i = -1;
                    clearInterval(interv0);
                    interv0 = setInterval(updateGauges, 1000); // restore a normal interval
                }
            }
        }

 else {
            // pass a data array to dashboard.js's UpdateDashboard(values for named gauges)
            for (var key in gauges) {
                readings[key] = readings[key] + 10 * Math.random() - 5;
                if (readings[key] < 0)
                    readings[key] = 0;
                if (readings[key] > 100)
                    readings[key] = 100;
                gauges[key].redraw(readings[key]);
            }
        }
    }

@beegee-tokyo
Copy link

I tried this awesome gauges and I like them.
For the first tests I used

<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js">

And it worked fine, Then, because I run it on an Intranet which doesn't have always internet access, I downloaded d3.js version 4.2.4 (the latest atm), put the d3.js file together with my html file and then it doesn't work anymore ??? The javascript stops with the error:

gauge.js:204 Uncaught TypeError: Cannot read property 'arc' of undefined

I include it with

<script type="text/javascript" src="d3.js"></script>

It works until d3.js V3.5.17 though and that is what I stick with for now.

@beegee-tokyo
Copy link

beegee-tokyo commented Sep 20, 2016

And another question, how do I resize the gauges in case the browser window is resized?
At the moment I use

var screenWidth = window.innerWidth;
var gaugeSize = screenWidth/8;

to calculate the size of 8 gauges to fit into the available window size. If the window size changes, I can catch it with

window.onresize = function(event) {}

But how do I resize the gauges???
I tried to change the gauges config parameters with

gauges[gauge_name_sol].config.size = gaugeSize*0.9 ;

for each gauge, but what to do next? If I create them again or just render them again, they just duplicate on the screen.
How can I dynamically resize the gauges? Or how do I delete existing gauges and create them again?

#EDIT

Never mind, found a solution with

window.onresize = function(event) {
    window.location.reload();
};

@grandtjs
Copy link

grandtjs commented Oct 4, 2016

Hi Guys!!!!
My name is Dario and I'am new in D3.js and need solve a problem.
In the index.html file is el following code:

  <script>              
      var gauges = [];
      function createGauge(name, label, min, max) {
          var config = {
                       size: 120,
                   label: label,
                   min: undefined != min ? min : 0,
                   max: undefined != max ? max : 100,
                   minorTicks: 5
                }

     var range = config.max - config.min;
     config.yellowZones = [{ from: config.min + range*0.75, to: config.min + range*0.9 }];
     config.redZones = [{ from: config.min + range*0.9, to: config.max }];

     gauges[name] = new Gauge(name + "GaugeContainer", config);
     gauges[name].render();
      }

      function createGauges() {
    createGauge("memory", "Memory");
    createGauge("cpu", "CPU");
    createGauge("network", "Network");
    //createGauge("test", "Test", -50, 50 );
      }

      function updateGauges() {
    for (var key in gauges) {
                            var value = getRandomValue(gauges[key])
                            gauges[key].redraw(value);
    }
      }

      function getRandomValue(gauge) {
    var overflow = 0; //10;
    return gauge.config.min - overflow + (gauge.config.max - gauge.config.min + overflow*2) *  Math.random();
      }

      function initialize() {
    createGauges();
    setInterval(updateGauges, 5000);
      }
</script>

And I need call the initialize function with an gaugeName parameter initialize("gaugeName")
and that the gauge is drawn in the but I do not how to do it.

Please, Can anyone help me with that

Thanks in advance

@jatin-optimus
Copy link

jatin-optimus commented Jan 21, 2017

Hello,

Can any one help me in writing gaugejs file to typescript.or if any gauge meter is available in angular2 with d3 combination please inform.

Thanks

@JamesTreleaven
Copy link

I hate to be the stick in the mud here, I really do - but I need a formal open source license attached to this for me to be able to use it. It would be terrific if you could attach one Tomer.

Cheers, James

@praveenuics
Copy link

@jatin-optimus could you please share the links of gauge chart with typescript if you have, thank you.

@robgee86
Copy link

robgee86 commented Feb 5, 2018

Hi,
I've forked and fixed an issue when moving away from vertical position.
You find it in my fork: https://gist.github.com/robgee86/50c20970c034df1e34f1cca9a6e9bc45 .
Thank you for the widget :)

@mirrageelpho
Copy link

im try port to vue js, but i have an error.
this is my code:

<template>
	<div>
		<div id="memoryGaugeContainer">
        </div>
	</div>
</template>

<script>
var Gauge = require('gauge')
export default {
  data () {
      return {
          gauges: []
      }
  },
  mounted () {
      this.$bar.finish()
      this.createGauge("memory", "MEMORY")
      this.setInterval(updateGauges, 1000)
  },
  methods: {
    createGauge(name, label, min, max)
    {
        var config = 
        {
            size: 120,
            label: label,
            min: undefined != min ? min : 0,
            max: undefined != max ? max : 100,
            minorTicks: 5
        }
        
        var range = config.max - config.min
        config.yellowZones = [{ from: config.min + range*0.75, to: config.min + range*0.9 }]
        config.redZones = [{ from: config.min + range*0.9, to: config.max }]
        
        this.gauges[name] = new Gauge(name + "GaugeContainer", config)
        this.gauges[name].render()
    },
    
    createGauges()
    {
        createGauge("memory", "MEMORY")
        // createGauge("cpu", "CPU")
        // createGauge("network", "Network")
        //createGauge("test", "Test", -50, 50 )
    },
    
    updateGauges()
    {
        for (var key in this.gauges)
        {
            var value = getRandomValue(this.gauges[key])
            this.gauges[key].redraw(value)
        }
    },
    
    getRandomValue(gauge)
    {
        var overflow = 0 //10
        return gauge.config.min - overflow + (gauge.config.max - gauge.config.min + overflow*2) *  Math.random()
    }
  }
}
</script>
`

this is an error:

vue.esm.js?efeb:578 [Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'isTTY' of undefined"

vue.esm.js?efeb:1717 TypeError: Cannot read property 'isTTY' of undefined
at Gauge.setWriteTo (index.js?b0bf:122)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment