众所周知R软件功能非常强大,可以很好的进行各类统计,并能输出图形。下面介绍一种R语言和C#进行通信的方法,并将R绘图结果显示到WinForm UI界面上的方法,文中介绍的很详细,需要
众所周知R软件功能非常强大,可以很好的进行各类统计,并能输出图形。下面介绍一种R语言和C#进行通信的方法,并将R绘图结果显示到WinForm UI界面上的方法,文中介绍的很详细,需要的朋友可以参考下。
众所周知R软件功能非常强大,可以很好的进行各类统计,并能输出图形。下面介绍一种R语言和C#进行通信的方法,并将R绘图结果显示到WinForm UI界面上的方法,文中介绍的很详细,需要的朋友可以参考下。
一、前提准备
安装r软件,需要安装32位的r软件,64位的调用会报错。另外就是讲r添加到电脑环境变量中。
打开r软件,安装包 scatterplot3d,演示需要用到此r包。
二、创建项目graphgeneratebyr,项目结构如下:

注意:这里需要引入rdotnet类库,可以自行下载:http://rdotnet.codeplex.com/
三、main窗体代码
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
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,结果如下:

总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对米米素材网的支持。
原文链接:http://www.cnblogs.com/isaboy/p/R_image_csharp_RDotNet.html
发表评论