好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#实现Windows Form调用R进行绘图与显示的方法

一、前提准备

安装r软件,需要安装32位的r软件,64位的调用会报错。另外就是讲r添加到电脑环境变量中。

打开r软件,安装包 scatterplot3d,演示需要用到此r包。

二、创建项目graphgeneratebyr,项目结构如下:

注意: 这里需要引入rdotnet类库,可以自行下载:http://rdotnet.codeplex.com/

三、main窗体代码

?

using system;

using system.collections.generic;

using system.componentmodel;

using system.data;

using system.drawing;

using system.linq;

using system.text;

using system.windows.forms;

 

namespace graphgeneratebyr

{

  using rdotnet;

  public partial class main : form

  {

   public main()

   {

    initializecomponent();

   }

   rengine engine = null ;

 

   string rcode = "" ;

   private void btnplot_click( object sender, eventargs e)

   {

    try

    {

     if ( this .txtrcode.text== "" )

     {

      rcode = @"library('scatterplot3d')

        z <- seq(-10, 10, 0.01)

        x <- cos(z)

        y <- sin(z)

        scatterplot3d(x, y, z, highlight.3d=true, col.axis='blue', col.grid='lightblue',main='3d绘图',pch=20)

        " ;

     }

     else

     {

      rcode = this .txtrcode.text;

     }

 

     //r.3.2.4

     engine = rengine.getinstance();

     engine.initialize();

     //图片加入guid,防止重名(还有一种就是先删除后保存)

     string rnd = system.guid.newguid().tostring().replace( "-" , "" );

     string filename = "i" + rnd+ "__rimage.png" ;

     engine.evaluate( string .format( "png(file='{0}',bg ='transparent',width={1},height={2})" , filename, this .ptbgraphic.width, this .ptbgraphic.height));

 

     //engine.evaluate(@"x <- (0:12) * pi / 12

     //    y <- cos(x)

     //    plot(x,y);

     //    ");

     engine.evaluate(rcode);

     engine.evaluate( "dev.off()" );

     string path = system.io.path.getfullpath(filename);

 

     bitmap image = new bitmap(path);

     ptbgraphic.image = image;

    }

    catch (exception ex)

    {

     messagebox.show(ex.message);

    }

  

   }

 

   private void main_formclosing( object sender, formclosingeventargs e)

   {

    if (engine!= null )

    {

     //clean up

     engine.dispose();

    }

   }

  }

}

四、运行:

单击plot后,调用默认r代码,结构如下:

输入合法的r绘图语句,再次单击plot,结果如下:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://www.cnblogs.com/isaboy/p/R_image_csharp_RDotNet.html

dy("nrwz");

查看更多关于C#实现Windows Form调用R进行绘图与显示的方法的详细内容...

  阅读:50次