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,结果如下:

总结

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

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。