Create graphics via R + JavaGD (JRI) in Java

来源:互联网 发布:如何加入淘宝网热卖 编辑:程序博客网 时间:2024/06/01 09:03

通过 JavaGD 创建 R 图像

File 1

import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.JButton;import javax.swing.JFrame;import org.rosuda.JRI.Rengine;import org.rosuda.javaGD.GDCanvas;public class TryR4 extends JFrame implements ActionListener{/** *  */private static final long serialVersionUID = 1L;private Rengine engine;public static GDCanvas gdc;private JButton jbgo;private int counter;public TryR4(){super.setTitle("My R Plot");super.setSize(600, 600);        // initialize GUI        jbgo = new JButton("Go");        gdc = new GDCanvas(600,600);        jbgo.addActionListener(this);        this.getContentPane().setLayout(new BorderLayout());        this.getContentPane().add(jbgo,BorderLayout.PAGE_START);        this.getContentPane().add(gdc,BorderLayout.PAGE_END);        this.pack();                // initialize R engine = new Rengine(new String[] {"--vanilla"}, false, null); engine.eval(".setenv <- if (exists(\"Sys.setenv\")) Sys.setenv else Sys.putenv");    engine.eval(".setenv(\"JAVAGD_CLASS_NAME\"=\"TryR4Interface\")");    engine.eval("library(JavaGD)");             this.setVisible(true);// initialize sth elsecounter = 1;}public static void main(String args[]){new TryR4();}@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif(e.getSource() == jbgo){engine.eval("JavaGD()");engine.eval("a <- rnorm(100)");engine.eval("plot(a,type=\"l\")");gdc.initRefresh();// save it to fileFile f = new File("c:\\playaround\\play2.png"); BufferedImage buffImg = new BufferedImage(gdc.getWidth(), gdc.getHeight(),BufferedImage.TYPE_INT_RGB);gdc.paintAll(buffImg.createGraphics()); try {ImageIO.write(buffImg, "png", f);} catch (IOException ex) {// TODO Auto-generated catch blockex.printStackTrace();}this.setTitle("Random number (" + String.valueOf(counter) + ")");counter ++;}}}

File 2 - Interface

import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import org.rosuda.javaGD.GDInterface;public class TryR4Interface extends GDInterface { public void gdOpen(double w, double h)  { c = TryR4.gdc; }}



原创粉丝点击