FLOT: How to make different colored points in same data series, connected by a line?

MegaMatt picture MegaMatt · Feb 17, 2010 · Viewed 9.7k times · Source

I think I may have stumbled onto a limitation of Flot, but I'm not sure. I'm trying to represent a single data series over time. The items' "State" is represented on the Y-Axis (there are 5 of them), and time is on the X-Axis (items can change states over time). I want the graph to have points and lines connecting those points for each data series.

In addition to tracking an item's State over time, I'd also like to represent it's "Status" at any of the particular points. This I would like to do by changing the color of the points. What this means is a single item may have different Statuses at different times, meaning for a single data series I need a line that connects different points (dots) of different colors.

The only thing I've seen so far is the ability to specify the color for all points in a given dataseries. Does anyone know if there's a way to specify colors individually?

Thanks.

Answer

kal3v picture kal3v · Sep 29, 2010

There you go mate. You need to use a draw hook.

$(function () {

  var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];
  var colors = ["#cc4444", "#ff0000", "#0000ff", "#00ff00"];
  var radius = [10, 20, 30, 40];

  function raw(plot, ctx) {
    var data = plot.getData();
    var axes = plot.getAxes();
    var offset = plot.getPlotOffset();
    for (var i = 0; i < data.length; i++) {
        var series = data[i];
        for (var j = 0; j < series.data.length; j++) {
            var color = colors[j];
            var d = (series.data[j]);
            var x = offset.left + axes.xaxis.p2c(d[0]);
            var y = offset.top + axes.yaxis.p2c(d[1]);
            var r = radius[j];                
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.arc(x,y,r,0,Math.PI*2,true);
            ctx.closePath();            
            ctx.fillStyle = color;
            ctx.fill();
        }    
    }
  };  

    var plot = $.plot(
          $("#placeholder"),
          [{ data: d2, points: { show: true } }],
          { hooks: { draw  : [raw] } }
  );  
});