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)境變量中。
打開(kāi)R軟件,安裝包 scatterplot3d,演示需要用到此R包。
二、創(chuàng)建項(xiàng)目GraphGenerateByR,項(xiàng)目結(jié)構(gòu)如下:

注意:這里需要引入RDotNet類(lèi)庫(kù),可以自行下載: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繪圖語(yǔ)句,再次單擊Plot,結(jié)果如下:

總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
C#實(shí)現(xiàn)json格式轉(zhuǎn)換成對(duì)象并更換key的方法
這篇文章主要介紹了C#實(shí)現(xiàn)json格式轉(zhuǎn)換成對(duì)象并更換key的方法,涉及C#操作json格式數(shù)據(jù)的相關(guān)技巧,需要的朋友可以參考下2015-06-06
C#反射實(shí)現(xiàn)插件式開(kāi)發(fā)的過(guò)程詳解
插件式架構(gòu),一種全新的、開(kāi)放性的、高擴(kuò)展性的架構(gòu)體系,插件式架構(gòu)設(shè)計(jì)好處很多,把擴(kuò)展功能從框架中剝離出來(lái),降低了框架的復(fù)雜度,讓框架更容易實(shí)現(xiàn),這篇文章主要介紹了C#反射實(shí)現(xiàn)插件式開(kāi)發(fā),需要的朋友可以參考下2023-09-09
C#中類(lèi)與結(jié)構(gòu)的區(qū)別實(shí)例分析
這篇文章主要介紹了C#中類(lèi)與結(jié)構(gòu)的區(qū)別,類(lèi)與結(jié)構(gòu)是C#初學(xué)者比較輕易混淆的概念,本文加以實(shí)例說(shuō)明,需要的朋友可以參考下2014-08-08
c# WPF中自定義加載時(shí)實(shí)現(xiàn)帶動(dòng)畫(huà)效果的Form和FormItem
這篇文章主要介紹了c# WPF中自定義加載時(shí)實(shí)現(xiàn)帶動(dòng)畫(huà)效果的Form和FormItem,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
WPF實(shí)現(xiàn)曲線數(shù)據(jù)展示
這篇文章將以動(dòng)數(shù)據(jù)分析為例為大家詳細(xì)介紹wpf實(shí)現(xiàn)曲線數(shù)據(jù)展示與函數(shù)曲線展示的方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考一下2024-12-12
C#運(yùn)用FileInfo類(lèi)實(shí)現(xiàn)拷貝文件的方法
這篇文章主要介紹了C#運(yùn)用FileInfo類(lèi)實(shí)現(xiàn)拷貝文件的方法,需要的朋友可以參考下2014-07-07

