Scientific graphics in C#
Posted on October 6, 2011 by Sol

The code for this tutorial is on GitHub: https://github.com/sol-prog/GraphDemo1

Imagine for a moment that you are stranded on a deserted island only with your laptop, your task is to write a compiled application that will let the user load a file with numbers and plot these on a graphic. For the sake of argument let's suppose you have a Windows based computer and, because Windows does not include any compiler by default, we'll also suppose you have Visual Studio 2010 installed. What would you do ?

Last week I was in a similar situation when my internet connection was down for two days and I was pressed by a client to add some 2D graphical capability to a C# application, the deadline for this project was quickly arriving and no third party library was allowed, only what is included by default with VS 2010. My solution was to use the Chart control for plotting the data on a Windows Form. The by-product of this project was this post in which I will show you how to add to a C# application a plotting area that will allow you to plot and save the graphics as high quality images.

This tutorial is intended to be self sustained even for a beginner so I will exemplify each step of building this app with screenshots. If you are an advanced C# coder feel free to skip the boilerplate sections. Next figure is an example of what kind of graphics you can create with the app we are going to build:

figure_9

In case you are wondering, this is the formula I've used for generating the data for the upper picture:

$$ x(t) = 2 \cdot a \cdot \cos (t) + a \cdot \cos (2 \cdot t) $$ $$ y(t) = \sin ( 2 \cdot a \cdot \sin (t) - a \cdot \sin (2 \cdot t)) $$

where:

$$ t \in 0...2 \cdot \pi $$

Open VS 2010 and create a new C# project: File->New Project, select Windows Forms Application and give a meaningful name to your app (GraphDemo in my case):

figure_1

Press OK. You should end up with a fresh Windows Form in your Design panel:

figure_2

From Solution Explorer right click Form1.cs and chose Rename, we will name this GraphDemo.cs. Press Yes when VS will ask if you want to rename this in all references.

Right click on the Form and select Properties, this will open a new Properties panel at right, change the value for Text from "Form1" to GraphDemo. You should see the new name on the Form. Change the Size property of the Form from 300,300 to 700,700 (of course you can achieve a similar result by dragging the lower right corner of the Form).

figure_3

From the left upper corner select Toolbox and drag a MenuStrip on the Form, write File in the small text box, also add free submenus to File: Open, Save and Exit:

figure_4

As you can guess by now, our application will allow the user to open a data file, plot the data and save the resulting image.

Let's add some code to the above submenus, double click on Exit, this will create for you an empty function that will be called when the user presses Exit:

1
2
3
4
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
	Application.Exit();
}

Try if you have any error in the above code by compiling and running the application: press F5 or go to Debug->Start Debugging. If you haven't made any error you should see the app running. Try to close the app using the Exit submenu!

Next, we will implement the Open functionality. In order to keep the code simple we will assume that the user will only load csv files (comma separated values), for e.g.:

1
2
3
4
5
x,y1,y2,y3
0,0,0.13,1
0.25,0.5,-0.22,2
0.5,1,0.8,3
1,2,0.7,4

Double click on GraphDemo[Design] at File->Open this, like before, will create an empty function for you, let's add the code that will let us load a csv file:

 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
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
	Stream myStream = null;
	OpenFileDialog ff = new OpenFileDialog();

	ff.InitialDirectory = "c:\\";
	ff.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
	ff.FilterIndex = 1;
	ff.RestoreDirectory = true;

	if (ff.ShowDialog() == DialogResult.OK)
	{
		try
		{
			if ((myStream = ff.OpenFile()) != null)
			{
				using (myStream)
				{
					// Add the code to load the csv file
					// ...
					// Close the stream
					myStream.Close();
				}
			}
		}
		catch (Exception err)
		{
			//Inform the user if we can't read the file
			MessageBox.Show(err.Message);
		}
	}
}

If you will copy the above code in GraphDemo.cs you will see that Stream is marked in red, this is because we didn't included System.IO in our code, we can let Visual Studio to solve this for us: right click on Stream select Resolve->using System.IO. The above function will only let us use the Open submenu to select a csv file from our computer, we still need to add the code that will actually read the file.

For actually reading a csv file from the disk we will create a new C# class. In Solution Explorer right click on  GraphDemo and select Add->New Item select Class and change the default name of this into something more meaningful say "Read.cs" press Add and you will end up with an empty class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GraphDemo
{
    class Read
    {
    }
}

We will add code for parsing a csv file and for storing and retrieving the header and the data. Let's start by creating a few private variables used for storing the data and the functions used for getting this data:

 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
...
namespace GraphDemo
{
    class Read
    {
        private string[] header;
        private float[,] data;
        private int nLines;
        private int nColumns;

        //constructor to be implemented
        public Read()
        {
        }

        //functions used for retrieving the data
        public int get_nLines()
        {
            return nLines;
        }

        public int get_nColumns()
        {
            return nColumns;
        }

        public float[,] get_Data()
        {
            return data;
        }

        public string[] get_Header()
        {
            return header;
        }
    }
}

Next, we implement the Read constructor:

 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
...
public Read(Stream myStream)
{
	string aux;
	string[] pieces;

	//read the file line by line
	StreamReader sr = new StreamReader(myStream);
	aux = sr.ReadLine();
	header = aux.Split(',');
	nColumns = header.Length;
	nLines = 0;
	while ((aux = sr.ReadLine()) != null)
	{
		if (aux.Length > 0) nLines++;
	}

	//read the numerical data from file in an array
	data = new float[nLines, nColumns];
	sr.BaseStream.Seek(0, 0);
	sr.ReadLine();
	for (int i = 0; i < nLines; i++)
	{
		aux = sr.ReadLine();
		pieces = aux.Split(',');
		for (int j = 0; j < nColumns; j++) data[i, j] = float.Parse(pieces[j]);
	}
	sr.Close();
}
...

Like before StreamReder will be underlined in red, right click and chose Resolve ...

We are ready to use the Read class, open GraphDemo.cs and add these lines of code in the function openToolStripMenuItem_Click:

1
2
3
4
5
6
7
8
9
...
using (myStream)
{
	rr = null;
	rr = new Read(myStream);
	// Close the stream
	myStream.Close();
}
...

In the above code we have used an undefined variable rr, which is a Read object. Scroll at the beginning of GraphDemo.cs and add "Read rr;" just before the GraphDemo constructor, this is how the code should look:

1
2
3
4
5
6
7
8
namespace GraphDemo
{
    public partial class GraphDemo : Form
    {
        Read rr;

        public GraphDemo()
        ...

Move to the Design panel from Toolbox and add on the Windows Form two Labels, two ComboBoxes, one Chart element and one Button. This is a possible arrangement for the GUI (feel free to move the elements as you see fit):

figure_5

Click on label1 and in the Solution Explorer->Properties modify the Text filed, which is currently "label1", to X-Axis. Apply the same procedure for label2, change the Text to Y-Axis.

Click on the left ComboBox and change his Name property to xBox, also change the Name property of the second ComboBox to yBox. Do not change the Text property for the ComboBoxes! Change the Name property of the Chart to "chart" and the Name of the Button to btnPlot. For btnPlot change the Text property from "button1" to "Plot".

Let's check if we have any error, press F5 or Debug->Start Debugging, your running app should look similar with the next figure:

figure_6

If it works than it is OK :D, you can close the application, we have work to do.

We'll start by populating the two ComboBoxes using the header of the input csv file. This will allow us to pick what variable to assign to the X-axis and Y-axis, the user should have the liberty to chose what variables he wants.

At a later stage of this tutorial I will show you how to plot multiple graphics on the same chart, for now we will keep this simple - pressing the Plot button will plot only the variables selected in the ComboBoxes. We could do this in the Open function after that file is loaded or in the Read class; for simplicity I will populate the ComboBoxes in GraphDemo.cs in the openToolStripMenuItem_Click function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
...
rr = new Read(myStream);
string[] header = rr.get_Header();
List<string> lX = new List<string>();
List<string> lY = new List<string>();
for (int i = 0; i < header.Length; i++)
{
	lX.Add(header[i]); lY.Add(header[i]);
}
//Populate the ComboBoxes
xBox.DataSource = lX;
yBox.DataSource = lY;
// Close the stream
myStream.Close();
...

Now it is a good time to run the code and actually load a csv file, you should be able to see the ComboBoxes populated with the names of the data columns stored in the input file.

We will create a new class file named "Plot.cs" using the same workflow as before (see the Read class). This class will do the actual drawing on the chart so we'll need to grant access to the Chart element, the two ComboBoxes and the Read object:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Drawing;

namespace GraphDemo
{
    class Plot
    {
        public Plot(Read rr, ComboBox xBox,ComboBox yBox,Chart chart)
        {
            // Code for drawing on the Chart
        }
    }
}

From the Design panel double click on the Plot button, this will create for you an empty function that will be called each time you press Plot. In this new function we will create a Plot object:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
private void btnPlot_Click(object sender, EventArgs e)
{
	if (rr != null)
	{
		Plot pl=new Plot(rr,xBox,yBox,chart);
	}
	else
	{
		MessageBox.Show("Error, no data to plot! Please load csv file");
		return;
	}
}

Now we are ready to implement the constructor function of Plot. In short, we will get the index of the variable to plot from xBox and yBox and we will plot the corresponding columns:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
        public Plot(Read rr, ComboBox xBox,ComboBox yBox,Chart chart)
        {
            int indX = xBox.SelectedIndex;
            int indY = yBox.SelectedIndex;
            float[,] data = rr.get_Data();
            int nLines = rr.get_nLines();

            chart.Series.Clear(); //ensure that the chart is empty
            chart.Series.Add("Series0");
            chart.Series[0].ChartType = SeriesChartType.Line;
            chart.Legends.Clear();
            for (int j = 0; j &lt; nLines; j++)
            {
                chart.Series[0].Points.AddXY(data[j,indX], data[j, indY]);
            }
        }

We now have a working version of our application! For testing purposes I've created a simple input file: the first column is made by values from 0 to 1, the second column was obtained by applying the sinus to the first column an so on. Let's see our program in action:

figure_7

Obviously we still have work to do, for e.g. we need to do something about the format of the numbers from the X axis, we could thicken a bit the blue line, add names on the axes and so on. We will work on fine tuning the aspect of the graph in the second part of this tutorial.

We still have to write the code for the Save submenu, for this double click Save in the Design panel and add this code in the newly created function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
	Stream myStream;
	SaveFileDialog ff = new SaveFileDialog();

	ff.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
	ff.FilterIndex = 1;
	ff.RestoreDirectory = true;

	if (ff.ShowDialog() == DialogResult.OK)
	{
		if ((myStream = ff.OpenFile()) != null)
		{
			using (myStream)
			{
				chart.SaveImage(myStream, System.Drawing.Imaging.ImageFormat.Jpeg);
			}
		}
	}
}

Next figure was obtained by using the Save menu:

figure_8

Read the second part of this tutorial - Scientific graphics with C# part 2.

If you want to learn more about C#, read the 4th edition of the C# programming book written by the C# language creator Anders Hejlsberg:

blog comments powered by Disqus