详细介绍使用C#实现Windows Form调用R进行绘图与显示的方法(图)


本文摘自PHP中文网,作者黄舟,侵删。

众所周知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,结果如下:

总结

以上就是详细介绍使用C#实现Windows Form调用R进行绘图与显示的方法(图)的详细内容!

相关阅读 >>

C# 将datatable数据导出到excel表格中的示例代码分享

详细介绍用C#描述数据结构3:arraylist的图文代码

手把手教你C#中指针的使用方法

C#中如何实现带百分比的进度条功能的示例代码分享

C#中常用的正则表达式总结分享

详细介绍C#语言中字符类char的使用方法总结

C#用什么软件编程?

C#日期格式转换的公共方法类的实现详解

C#winform创建excel文件的示例代码分享

.net框架-微软给出的C#编程风格代码实例

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...