how to add a needle or dial to gauge indicator in plotly.js?

Viewed 721

I'm having hard time adding the dial/needle to the gauge chart from plotly.js.

gauge without needle : As you could see in the image above it's gauge chart without any needle.

gauge with needle : I want to build something similar to "gauge with needle", which is giving me hard time.

my code for "gauge without needle/dial" :

`https://codepen.io/vivek137/pen/rNyembX`
1 Answers

You will need to add an arrow annotation on top of your gauge chart. I answered a similar question and in that answer, I described how you can use polar coordinates to find out the ending position x and y for your arrow. Under the hood, the gauge chart you made has an x-range of [0,1] and a y-range of [0,1], so the starting point is ax=0.5 and ax=0 which are both parameters for your annotation. Then the ending position is given by x = 0.5 + r * cos(theta) and y = r * sin(theta) where theta is the angle taken from the right side of the chart and moving counterclockwise.

One thing you should keep in mind is that if the render area in your browser isn't a perfect square, then the r and theta values may need to be adjusted. For example, in my codepen, I used r=0.7, theta=93.5 to point to the 40.

let data = [
    {
        mode: "gauge",
        type: "indicator",
        value: 40,

        gauge: {
            shape: "angular",
            bar: {
                color: "blue",
                line: {
                    color: "red",
                    width: 4
                },  
                thickness: 0
            },
            bgcolor: "#388",
            bordercolor: "#a89d32",
            borderwidth: 3,
            axis: {
                range: [0,100],
                visible: true,
                tickmode: "array",
                tickvals: [5, 10, 40, 80, 100],
                ticks: "outside"
            },
            steps: [
                {
                    range: [0, 40],
                    color: "#9032a8"
                }
            ]
        }
    }
]

var theta = 93.5
var r = 0.7
var x_head = r * Math.cos(Math.PI/180*theta)
var y_head = r * Math.sin(Math.PI/180*theta)

let layout = {
  xaxis: {range: [0, 1], showgrid: false, 'zeroline': false, 'visible': false},
  yaxis: {range: [0, 1], showgrid: false, 'zeroline': false, 'visible': false},
  showlegend: false,
  annotations: [
    {
      ax: 0.5,
      ay: 0,
      axref: 'x',
      ayref: 'y',
      x: 0.5+x_head,
      y: y_head,
      xref: 'x',
      yref: 'y',
      showarrow: true,
      arrowhead: 9,
    }
  ]
};
Plotly.newPlot('gauge1', data, layout)

enter image description here

Related