C#實現(xiàn)Windows Form調用R進行繪圖與顯示的方法
更新時間:2017年02月27日 11:57:29 作者:JackWang-CUMT
眾所周知R軟件功能非常強大,可以很好的進行各類統(tǒng)計,并能輸出圖形。下面介紹一種R語言和C#進行通信的方法,并將R繪圖結果顯示到WinForm UI界面上的方法,文中介紹的很詳細,需要的朋友可以參考下。
一、前提準備
安裝R軟件,需要安裝32位的R軟件,64位的調用會報錯。另外就是講R添加到電腦環(huán)境變量中。
打開R軟件,安裝包 scatterplot3d,演示需要用到此R包。
二、創(chuàng)建項目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,結果如下:

總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
C#使用xsd文件驗證XML格式是否正確的實現(xiàn)方法
這篇文章主要介紹了C#使用xsd文件驗證XML格式是否正確的實現(xiàn)方法,結合實例形式分析了C#針對xml文件的創(chuàng)建、驗證相關操作技巧,需要的朋友可以參考下2017-01-01
C#實現(xiàn)Excel數據導入到SQL server數據庫
這篇文章主要為大家詳細介紹了在C#中如何實現(xiàn)Excel數據導入到SQL server數據庫中,文中的示例代碼簡潔易懂,希望對大家有一定的幫助2024-03-03

