众所周知r软件功能非常强大,可以很好的进行各类统计,并能输出图形。下面介绍一种r语言和c#进行通信的方法,并将r绘图结果显示到winform ui界面上的方法,文中介绍的很详细,需要的朋友可以参考下。
一、前提准备
安装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,结果如下:
总结
以上就是详细介绍使用c#实现windows form调用r进行绘图与显示的方法(图)的详细内容。