詳細介紹使用C#實作Windows Form呼叫R進行繪圖與顯示的方法(圖)

黄舟
發布: 2017-03-17 13:10:21
原創
2219 人瀏覽過

眾所周知R軟體功能非常強大,可以很好的進行各類統計,並能輸出圖形。以下介紹一種R語言和C#進行通訊的方法,並將R繪圖結果顯示到WinForm UI介面上的方法,文中介紹的很詳細,需要的朋友可以參考下。

一、前提準備

安裝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=&#39;blue&#39;, col.grid=&#39;lightblue&#39;,main=&#39;3d绘图&#39;,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=&#39;{0}&#39;,bg =&#39;transparent&#39;,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,結果如下:

##總結#

以上是詳細介紹使用C#實作Windows Form呼叫R進行繪圖與顯示的方法(圖)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!