Use R in C#: Create a data plot and save it as png

As shown in a previously article it is easy to integrate R in a C# application by using R.Net. Within this article I want to explain how to create a data visualization plot and export it as png file.

 
Use Case
The R visualization functionality should be shown based on the correlation between the size and population of countries. The data in this example is based on real data with size in thousand square kilometers and population in thousand inhabitants.

 
Prepare vectors
At first the data vectors must be prepared. The following code shows the C# list with the data and the according R vectors. Later on we will access the data by using the alias names set by using “SetSymbol”.

List<int> size = new List<int>() { 29, 33, 51, 110, 357, 45, 338, 543, 132, 70, 103, 301, 146, 10, 56, 243, 238 };
List<int> population = new List<int>() { 3162, 11142, 3834, 7305, 81890, 1339, 5414, 65697, 11280, 4589, 320, 60918, 480, 1806, 4267, 63228, 21327 };

IntegerVector sizeVector = engine.CreateIntegerVector(size);
engine.SetSymbol("size", sizeVector);

IntegerVector populationVector = engine.CreateIntegerVector(population);
engine.SetSymbol("population", populationVector);

 
To define the target file we will create a file name vector.

string fileName;

fileName = "C:\\myplot.png";

CharacterVector fileNameVector = engine.CreateCharacterVector(new []{fileName});
engine.SetSymbol("fileName", fileNameVector);

 
Create plot
The data visualization is done by using the “plot” function. We will put in the data truncated with the “” sign. This will create a scatterplot of the data with population as the target variable. Furthermore we calculate the linear regression between the two vectors and add a regression line to the plot.

engine.Evaluate("reg <- lm(population~size)");
engine.Evaluate("plot(population~size)");
engine.Evaluate("abline(reg)");

 
Export plot
The plot data can be exported as file. R supports several file formats. Within this example I want to create a png file. This file can be created by using the “png” command in front of the “plot” call. In this case the plot data will be written to the file. The file itself is locked by the R environment because you may add some more data, e.g. the regression line. So if you want to access the file outside of the R engine you have to release it first. This is done with the “dev.off()” function.

engine.Evaluate("png(filename=fileName, width=6, height=6, units='in', res=100)");
engine.Evaluate("plot(population~size)");
engine.Evaluate("dev.off()");

 
If you want to change the size or the quality of the png file you may adapt the width, height or resolution (“res”) parameter of the “png” function.

 
Application
The following source code shows the complete example as console application.

using System;
using RDotNet;
using System.Collections.Generic;

namespace R_Plot_LinearRegression
{
    class Program
    {
        static void Main(string[] args)
        {            
            REngine engine;
            string fileName;

            //init the R engine            
            REngine.SetEnvironmentVariables();
            engine = REngine.GetInstance();
            engine.Initialize();

            //prepare data
            List<int> size = new List<int>() { 29, 33, 51, 110, 357, 45, 338, 543, 132, 70, 103, 301, 146, 10, 56, 243, 238 };
            List<int> population = new List<int>() { 3162, 11142, 3834, 7305, 81890, 1339, 5414, 65697, 11280, 4589, 320, 60918, 480, 1806, 4267, 63228, 21327 };

            fileName = "C:\\Users\\ofunke\\Desktop\\myplot.png";

            //calculate
            IntegerVector sizeVector = engine.CreateIntegerVector(size);
            engine.SetSymbol("size", sizeVector);

            IntegerVector populationVector = engine.CreateIntegerVector(population);
            engine.SetSymbol("population", populationVector);

            CharacterVector fileNameVector = engine.CreateCharacterVector(new []{fileName});
            engine.SetSymbol("fileName", fileNameVector);

            engine.Evaluate("reg <- lm(population~size)");
            engine.Evaluate("png(filename=fileName, width=6, height=6, units='in', res=100)");
            engine.Evaluate("plot(population~size)");
            engine.Evaluate("abline(reg)");
            engine.Evaluate("dev.off()");

            //clean up
            engine.Dispose();

            //output
            Console.WriteLine("");            
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}
Werbung
Dieser Beitrag wurde unter .NET, C#, R veröffentlicht. Setze ein Lesezeichen auf den Permalink.

2 Antworten zu Use R in C#: Create a data plot and save it as png

  1. Fernando schreibt:

    How can I use a route inside the project? like „~/Content/Images/plotImage.png“

  2. Rhonda Roaming schreibt:

    Thaanks great blog post

Schreibe eine Antwort zu Rhonda Roaming Antwort abbrechen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s