Search code examples
c#winformsgraphmschart

Graph add time to every value in a Array


I'm getting an int array from a file

Example:

0: 56
1: 57
2: 58
3: 59
4: 60
5: 61
6: 62
7: 63

I've taken all the data from it using Linq and now i've got an INT-Array

How can I tell the Graph that every value differs 15 minutes from the last one so it can draw properly?

The X-Series is set to "time" already

How i read the data from the file:

int[] data = File
              .ReadLines(file)
              .Select(line => line.Substring(line.IndexOf(':') + 1))
              .Where(line => !string.IsNullOrWhiteSpace(line))
              .Select(line => int.Parse(line))
              .ToArray();

              chart1.DataSource = data;

Solution

    • Step 1: Make sure the x-values are in fact valid and correct times.

    • Step 2 format the axis to show the correct interval.

    Example using direct datapoint adding:

    DateTime start = DateTime.Now;
    chart.Series[0].XValueType = ChartValueType.DateTime;
    
    //loop over x..:
      chart.Series[0].Points.AddXY(start.AddMinutes(x * 15, start), yValue);
    

    You can use the same function to convert the integers you have to ascending 15 minute timesteps in your datasource.

    To do the formatting you may use code like this:

    Axis ax = chart.ChartAreas[0].AxisX;
    
    ax.LabelStyle.Format = "HH:mm";
    ax.IntervalType = DateTimeIntervalType.Minutes;
    ax.Interval = 15;
    

    enter image description here

    Update:

    The answer shows how to convert the data to a suitable form and how to format the chart. It ignored the way you aquired the data.

    You completely threw away the 1st part of the lines. You also never show the full code of your data binding.

    Here is 1st a Linq code that reads in both parts of the data:

    var data = File.ReadLines(file)
        .Where(line => !string.IsNullOrWhiteSpace(line))
        .Select( line => line.Split(':') )
        .Select( parts => new { x = int.Parse(parts[0]), y = int.Parse(parts[1]) } )
        .ToArray();
    

    But the x-values still are just integers. Here is a code that instead converts them to a DateTimes, calculating 15-minute intervals from each int:

    DateTime start = DateTime.Now;
    
    var chartData = File.ReadLines(file)
        .Where(line => !string.IsNullOrWhiteSpace(line))
        .Select( line => line.Split(':') )
        .Select( parts => new { x = start.AddMinutes(int.Parse(parts[0]) * 15), y = int.Parse(parts[1]) } )
        .ToArray();
    

    You could bind them to the chart like this:

    s.XValueMember = "x";
    s.YValueMembers = "y";
    chart.DataSource = chartData;
    

    Note that you will need to zoom into the chart with 400+ points to see the 15 minute intervals..