Search code examples
dygraphs

Multiple colors per axis based on value


I'm using awesome dygraphs library to draw data. Values range from 0 to 100. Is it possible to have 1 color for data between 0-50, other color for 51-80 and another color for 81-100.

The point is to better demonstrate data. 0-50 is normal (green), 51-80 is warning (yellow) and 81-100 is alarm (red).

I know dygraphs has highlighted regions (http://dygraphs.com/gallery/#g/highlighted-region) but this is not it.


Solution

  • You can use the drawPointCallback feature to do this.

    new Dygraph(div, data, {
      drawPointCallback: function(g, seriesName, canvasContext, cx, cy, seriesColor, pointSize, row) {
        var col = g.indexFromSetName(seriesName);
        var val = g.getValue(row, col);
        var color = '';
        if (val >= 0 && val <= 50) {
          color = 'green';
        } else if (val > 50 && val <= 80) {
          color = 'yellow';
        } else if (val > 80) {
          color = 'red';
        }
        if (color) {
          canvasContext.beginPath();
          canvasContext.fillStyle = color;
          canvasContext.strokeStyle = seriesColor;
          canvasContext.arc(cx, cy, pointSize, 0, 2 * Math.PI, false);
          canvasContext.fill();
          canvasContext.stroke();
        }
      }, 
      drawPoints: true,
      pointSize: 5,
      highlightCircleSize: 8
    });
    

    See fiddle.