Winforms Chart - draw a allowed area on line chart

2.5k views Asked by At

How can I draw the gray area on the chart (allowed range of the signal)?
I use the Winforms and standard Microsoft System.Windows.Forms.DataVisualization classes.
It should be the custom range, the meaning that the starting Y point could be not zero only.
The points I get online, at run time, one by one.

UPDATE:

I tried the StripLine - it's ok, but I don't know how to define the starting point in 2d. It can be set on X only or on Y only. I tried to use the second chart (Area), but it's not what I need...

UPDATE2:
Thanks to @Reza Aghaei!!!

Here the code that works great:

void drawAllowedArea(Point startPoint, Point endPoint, PaintEventArgs e)
{
      var l = (float)chart1.ChartAreas[0].AxisX.ValueToPixelPosition(startPoint.X);
      var t = (float)chart1.ChartAreas[0].AxisY.ValueToPixelPosition(endPoint.Y);
      var r = (float)chart1.ChartAreas[0].AxisX.ValueToPixelPosition(endPoint.X);
      var b = (float)chart1.ChartAreas[0].AxisY.ValueToPixelPosition(startPoint.Y);
      var rect = RectangleF.FromLTRB(l, t, r, b);
      using (var br = new SolidBrush(Color.FromArgb(100, Color.Blue))) 
      {
           e.Graphics.FillRectangle(br, rect.X, rect.Y, rect.Width, rect.Height);
      }
      e.Graphics.DrawRectangle(Pens.Red, rect.X, rect.Y, rect.Width, rect.Height);
}

//and use this function in chart1_Paint event:
void chart1_Paint(object sender, PaintEventArgs e)
{
      drawAllowedArea(new Point(20, 50000), new Point(40, 100000), e);
}

END OF UPDATE ---------------------------------------------------------

enter image description here

Thank you a lot!

1

There are 1 answers

0
Reza Aghaei On BEST ANSWER

You can handle Paint event of Chart control and draw a rectangle on it. To get coordinates of the rectangle based on x-axis and y-axis values you can use ValueToPixelPosition method of axis. For example:

void chart1_Paint(object sender, PaintEventArgs e)
{
    var l = (float)chart1.ChartAreas[0].AxisX.ValueToPixelPosition(3.7);
    var t = (float)chart1.ChartAreas[0].AxisY.ValueToPixelPosition(45);
    var r = (float)chart1.ChartAreas[0].AxisX.ValueToPixelPosition(7.2);
    var b = (float)chart1.ChartAreas[0].AxisY.ValueToPixelPosition(31);
    var rect = RectangleF.FromLTRB(l, t, r, b);
    using (var br = new SolidBrush(Color.FromArgb(100,Color.Blue)))
        e.Graphics.FillRectangle(br, rect.X, rect.Y, rect.Width, rect.Height);
    e.Graphics.DrawRectangle(Pens.Red, rect.X, rect.Y, rect.Width, rect.Height);
}

Above values are just random values for test, you should use actual values of your x-axis and y-axis:

  • l: left of the rectangle (from x-axis)
  • t: top of the rectangle (from y-axis)
  • r: right of the rectangle (from x-axis)
  • b: bottom of the rectangle (from y-axis)

If you know values are int, you can cast them to int instead of float which I used for test.