rakib
rakib

Reputation: 197

C# : How to get area between two series in chart in C#?

I have two series in a chart in c#. I just want to get the area between these two series. These series are connect with each other.

I have attached the chart image.

enter image description here

Here there are two series. For example Series1 and Series2. If series2 cross above the series1 then that area will not be consider. Only where series2 is below series1 this area only have to calculate.

Upvotes: 4

Views: 1042

Answers (2)

Kahbazi
Kahbazi

Reputation: 15005

static void Main(string[] args)
{
    List<Point> Points1 = new List<Point>();
    //Points1.Add(); assign your series points

    List<Point> Points2 = new List<Point>();
    //Points2.Add(); assign your series points

    Series Series1 = new Series(Points1);
    Series Series2 = new Series(Points2);

    var betweenArea = Math.Abs(Series1.Area() - Series2.Area());
}

public class Series
{

    List<Point> Points { get; set; }

    public Series(List<Point> points)
    {
        Points = points;
    }

    public double Area()
    {
        double Area = 0;
        var points = Points.OrderBy(P => P.X).ToList();
        for (int i = 0; i < points.Count - 1; i++)
        {
            Point Point1;
            Point Point2;
            if (points[i].Y < points[i + 1].Y)
            {
                Point1 = points[i];
                Point2 = points[i + 1];
            }
            else
             {
                 Point1 = points[i + 1];
                 Point2 = points[i];
             }

             Area += Point1.Y * (Math.Abs(Point1.X - Point2.X));

            Area += ((Math.Abs(Point1.Y - Point2.Y)) * (Math.Abs(Point1.X - Point2.X)))/2;
        }

        return Area;
    }
}

public class Point
{
    public double X { get; set; }
    public double Y { get; set; }
}

Upvotes: 3

TaW
TaW

Reputation: 54433

You can color the area, see here, but calculating its area it is a matter of math.

Here is how I would do it:

  • first for each point in each series add/insert the point directly above/ below it.
  • Now you have a series of polygons with parallel vertical edges.
  • The area of each can be split in three parts: the center rectangle and the top and bottom triangle
  • width and height are knonw, so the areas are w*h for the rectangles and w*h/2 for the triangles.
  • the corresponding points are found by interpolating the previous and next points in the corresponding series.

Just a number of simple steps. The harder part is to keep track of the start and stop points and the empty and special cases..

  • The normal case is green/magenta below.
  • If a side if zero there is no problem
  • If a point from series1 is higher or lower than the next on in series2 you need to add two more points and do the calcualting over a tilted polygon. See the orange/cyan lines below!

enter image description here

Upvotes: 2

Related Questions