一、前提準備
安裝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,結果如下:
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答