Search code examples
flot

Can Flot plot a vector field?


I have some JS that explores some properties of a planar model and the mechanism that causes a phase transition in a lattice of spins. One indicator of a phase transition is the way the spins are oriented in the lattice, and for that I would like to plot a vector field. Can Flot do that?


Solution

  • Yes, you can do this with one small change to the flot library. In the drawSeriesPoints(series) function (line 1986 in version 0.7) change the line

    symbol(ctx, x, y, radius, shadow);
    

    to this

    symbol(ctx, x, y, radius, shadow, series, Math.floor(i / ps));
    

    This is done so that you can access the datapoint when drawing it.

    Format your data points in the form [x coordinate, y coordinate, vector angle, vector length] and use a custom symbol function like this:

    function vector(ctx, x, y, radius, shadow, series, index) {
    
      var vectorAngle = series.data[index][2]; // in radians
      var vectorLength = series.data[index][3]; // in pixels
    
      var bottom = [Math.round(x + vectorLength * Math.sin(vectorAngle)), Math.round(y - vectorLength * Math.cos(vectorAngle))];
      var top = [Math.round(x - vectorLength * Math.sin(vectorAngle)), Math.round(y + vectorLength * Math.cos(vectorAngle))];
      var left = [top[0] - (top[0] - bottom[0]) / 4 + (top[1] - bottom[1]) / 4, top[1] - (top[1] - bottom[1]) / 4 - (top[0] - bottom[0]) / 4];
      var right = [top[0] - (top[0] - bottom[0]) / 4 - (top[1] - bottom[1]) / 4, top[1] - (top[1] - bottom[1]) / 4 + (top[0] - bottom[0]) / 4];
    
      ctx.beginPath();
      ctx.moveTo(top[0], top[1]);
      ctx.lineTo(left[0], left[1]);
      ctx.lineTo(right[0], right[1]);
      ctx.lineTo(top[0], top[1]);
      ctx.closePath();
      ctx.fillStyle = series.color;
      ctx.fill();
    
      ctx.beginPath();
      ctx.moveTo(top[0], top[1])
      ctx.lineTo(bottom[0], bottom[1]);
      ctx.stroke();
    
      ctx.beginPath();
      ctx.moveTo(x, y);
    }
    

    Complete example as fiddle.