Hi there, now I am going to show you how to create an auto updating plot in c# based on timer. The complete video guide is available on my Youtube Channel.
I have put the full code at the end of this page.
To begin, create a simple template consisted of "Chart" and "Button" like this :
Don't forget to change series type to "line'. To do that, click chart, see properties and find "Series", from the collection, change the "ChartType" to "Line".
Create a new timer :
System.Windows.Forms.Timer PlotTimer = new System.Windows.Forms.Timer();
Create a void function that can be called each by the timer. This function is used to generated data and plot them to the chart. This is the code :
{
int length = 400;
double[] x = new double[length];
double[] y = new double[length];
Random rd = new Random();
double amplitude = rd.Next(0, length);
chart1.Series[0].Points.Clear();
for (int i = 0; i < length; i++)
{
x[i] = i;
y[i] = amplitude * (Math.Sin(i));
chart1.Series[0].Points.AddXY(x[i], y[i]);
}
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = length;
}
Now, connect the Timer and the function you have created :
PlotTimer.Tick += new EventHandler(RealTimePlot);
and set the speed of plot in miliseconds :
Finally, under the push button, put a code to start and stop the plot. It is just like this :
if (PlotTimer.Enabled == true)
}
else
PlotTimer.Enabled = true;
}
Compile and Run. You should have a program like this :
Here is the complete code in visual C# :
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
System.Windows.Forms.Timer PlotTimer = new System.Windows.Forms.Timer();
private void RealTimePlot(Object myObject, EventArgs myEventArgs)
{
int length = 400;
double[] x = new double[length];
double[] y = new double[length];
Random rd = new Random();
double amplitude = rd.Next(0, length);
chart1.Series[0].Points.Clear();
for (int i = 0; i < length; i++)
{
x[i] = i;
y[i] = amplitude * (Math.Sin(i));
chart1.Series[0].Points.AddXY(x[i], y[i]);
}
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = length;
}
private void Form1_Load(object sender, EventArgs e)
{
PlotTimer.Interval = 400;
PlotTimer.Tick += new EventHandler(RealTimePlot);
}
private void button1_Click(object sender, EventArgs e)
{
if (PlotTimer.Enabled == true)
{
PlotTimer.Enabled = false;
}
else
{
PlotTimer.Enabled = true;
}
}
private void chart1_Click(object sender, EventArgs e)
{
}
}
}