Last active
May 23, 2017 15:05
-
-
Save mjkallen/8299891 to your computer and use it in GitHub Desktop.
A basic Processing sketch -using the grafica plotting library- in Java with R integration using Renjin. This sketch calls R's runif() command to generate 100 random numbers, multiplies these by 10 and creates a line plot of the result.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.script.*; | |
/* The Processing.core.PApplet jar is included in the Processing.org download. | |
* Search Google for "Processing Eclipse" to find instructions on how to get this | |
* dependency available in Eclipse. | |
*/ | |
import processing.core.PApplet; | |
/* 'grafica' is a third-party library for Processing.org, see https://github.com/jagracar/grafica. | |
* The easiest thing to do is to copy the Java src/grafica directrory into your own project. | |
*/ | |
import grafica.*; | |
/* Download the (latest version of the) Renjin script engine from | |
* http://nexus.bedatadriven.com/content/groups/public/org/renjin/renjin-script-engine/ | |
* Use the "jar-with-dependencies" from this link. | |
*/ | |
import org.renjin.sexp.*; | |
public class Sketch1 extends PApplet { | |
// Processing setup method | |
public void setup() { | |
size(500, 350); | |
background(150); | |
// Prepare the points for the plot | |
int nPoints = 100; | |
GPointsArray points = new GPointsArray(nPoints); | |
try { | |
points = Random(nPoints); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
// Create a new plot and set its position on the screen | |
GPlot plot = new GPlot(this); | |
plot.setPos(25, 25); | |
// Set the plot title and the axis labels | |
plot.setPoints(points); | |
plot.getXAxis().setAxisLabelText("x axis"); | |
plot.getYAxis().setAxisLabelText("y axis"); | |
plot.setTitleText("A very simple example"); | |
// Draw it! | |
plot.defaultDraw(); | |
} | |
GPointsArray Random(int nPoints) throws Exception { | |
GPointsArray points = new GPointsArray(nPoints); | |
// create a script engine manager | |
ScriptEngineManager factory = new ScriptEngineManager(); | |
// create a Renjin engine | |
ScriptEngine engine = factory.getEngineByName("Renjin"); | |
// evaluate R code from String | |
DoubleVector res = (DoubleVector)engine.eval("runif(100)"); | |
for(int i = 0; i < nPoints; i++){ | |
points.add(i, (float)(10*res.getElementAsDouble(i))); | |
} | |
return points; | |
} | |
// Processing draw method | |
/*public void draw() { | |
}*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment