C#實(shí)現(xiàn)Windows Form調(diào)用R進(jìn)行繪圖與顯示的方法
一、前提準(zhǔn)備
安裝R軟件,需要安裝32位的R軟件,64位的調(diào)用會(huì)報(bào)錯(cuò)。另外就是講R添加到電腦環(huán)境變量中。
打開R軟件,安裝包 scatterplot3d,演示需要用到此R包。
二、創(chuàng)建項(xiàng)目GraphGenerateByR,項(xiàng)目結(jié)構(gòu)如下:

注意:這里需要引入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();
}
}
}
}
四、運(yùn)行:
單擊plot后,調(diào)用默認(rèn)R代碼,結(jié)構(gòu)如下:

輸入合法的R繪圖語句,再次單擊Plot,結(jié)果如下:

總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
C#使用xsd文件驗(yàn)證XML格式是否正確的實(shí)現(xiàn)方法
這篇文章主要介紹了C#使用xsd文件驗(yàn)證XML格式是否正確的實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了C#針對(duì)xml文件的創(chuàng)建、驗(yàn)證相關(guān)操作技巧,需要的朋友可以參考下2017-01-01
C#實(shí)現(xiàn)Excel數(shù)據(jù)導(dǎo)入到SQL server數(shù)據(jù)庫
這篇文章主要為大家詳細(xì)介紹了在C#中如何實(shí)現(xiàn)Excel數(shù)據(jù)導(dǎo)入到SQL server數(shù)據(jù)庫中,文中的示例代碼簡(jiǎn)潔易懂,希望對(duì)大家有一定的幫助2024-03-03
C#實(shí)現(xiàn)Word轉(zhuǎn)PDF的方法總結(jié)
這篇文章主要為大家詳細(xì)介紹了C#中實(shí)現(xiàn)Word轉(zhuǎn)PDF的常用方法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,有需要的小伙伴可以參考下2023-10-10
C#實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能(窗體)
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01

