Wednesday, December 24, 2014

Processing - graphs,plots in realtime.

Line,scatter plots with labels and continous updating can be done with Graph2D and the mechanics of actually plotting a graph are handled automatically. 

For a simple bar chart you could do something like this ...

simple bar graph with processing


void setup()
{
 size(800, 600);
}

void singleBar(int barId, float val, String title)
{

  int screen_pos_x = 10;
  int screen_pos_y = 10;

  int fontSz = 10;
  float barHeight = fontSz + val*10;
  int bar_width = 64;
  int x_pos = screen_pos_x + (bar_width * barId);
  int y_pos = screen_pos_y;
 
  fill(barId*15, barId*25, 25+ barId*25);
  rect(50+x_pos,y_pos,bar_width,barHeight);
  textSize( fontSz );
 
  fill(255,255,255);
  text(title + " " + val,50+x_pos,y_pos,bar_width,barHeight);
}



void draw()

  background(255);
  int i = 0;
  for(i = 1; i < 10; i++)
  {
    singleBar(i,i*5,"v" +i);
  } 

}


Here's a realtime sine wave plot ... in this case the data source is simply sin(angle)*50.
We can change the data source to be streamed machine data from a dweet.io or any kind of plot. So here's our simple Graph2D plot of a sine wave that is continously updated, X axis is time, Y axis is value.


sin(angle)*50 realtime plot



// Need the graph2D library installed ...
 
import org.gwoptics.graphics.graph2D.Graph2D;
import org.gwoptics.graphics.graph2D.traces.ILine2DEquation;
import org.gwoptics.graphics.graph2D.traces.RollingLine2DTrace;


// Data sources have 'signature' method 'computePoint' we just change the body
// to return our new 'data source'.

class dataStreamA implements ILine2DEquation{
  public double computePoint(double x,int pos) { 
     if( (ang+=0.2) >= 359.8) { 
        ang=0.0;
     }
     return sin(ang)*50;
  }   
  private float ang;
 
}

RollingLine2DTrace r;
Graph2D g;

void setup()
{
  size(800,600);
  r = new RollingLine2DTrace(new dataStreamA() ,50,0.01f);
  r.setTraceColour(0,0,255);
  g = new Graph2D(this, 600, 480, false);
  g.setYAxisMax(100);
  g.setYAxisMin(-100);
  g.addTrace(r);
  g.position.y = 50;
  g.position.x = 100;
  g.setYAxisTickSpacing(5.0f);
  g.setXAxisTickSpacing(0.5f);
  g.setXAxisMax(2);
  g.setYAxisLabel("sin");
  g.setNoBackground();
}


void draw()
{
  background(255);
  g.draw();
}



No comments:

Post a Comment