bricx
bricx

Reputation: 663

How to embed a R plot in a Winform in c#?

I am using R.NET to perform computation in my C# application and now I'd like to display the results in a Winform.

Anyone could advise on how to embed a R plot in a winform using R.NET ?

I found the below post which seems outdated as I can't find any reference nor Nuget package for the RNETGraph namespace that they use. The link referenced in the post have also been archived.

display multiple R Embedded Graph in multiple panel winform c#

And I would like to avoid the ugly solution of saving the image and then loading it in a PictureBox as I need to change the plot dynamically according to user input.

Thanks

Upvotes: 2

Views: 986

Answers (2)

Hunter2
Hunter2

Reputation: 65

You can use Dieter Menne's RGraphHooks to display R's plot output in a graphical WinForms element (e.g. a Windows.Forms.Panel). RGraphHooks has a dependency to Dino Esposito's Win32 hooks library.

Usage of RGraphHooks is quite simple. See this blog post by Peter Dai Dinh for a small demo program.

What you basically do is, you attach an RGrapHook to a specific control in your WinForms GUI and then wrap your engine.Evaluate("plot(...)") in this hook:

RGraphAppHook cbt = new RGraphAppHook { GraphControl = panelForPlot };

cbt.Install();
engine.Evaluate("plot(rnorm(100))");
cbt.Uninstall();

Upvotes: 1

Prometheus
Prometheus

Reputation: 2017

I never got hold of R.NET - documentation just wasn't very clear.

There is another option, however. You can use the command line to transfer arguments from your C# application to your R.Script.

For example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strCmdText;
            strCmdText = "Rscript.exe [directory here]\\script.R 10 arg2"; //what comes after script.R are the arguments you are passing. 
            System.Diagnostics.Process.Start("CMD.exe", strCmdText);
        }
    }
}

Then, it is very easy to retrieve the arguments in the R Script. Just use:

args <- commandArgs(trailingOnly = TRUE)

var1 <- args[1]  #Argument 1
var2 <- args[2]  #Argument 2

Addendum: Please note, you should have your RScript.exe in the environment variables in order to get the above to work.

Upvotes: 0

Related Questions