Search code examples
c#winformsmschart

How to draw vertical line on mschart that fills graph but isn't infinite?


I am trying to draw a vertical line that is anchored to a point. I tried to use the height of my Y axis which is fixed to draw the line, but it wasn't centered correctly. So right now I have an infinite line, but that I want is the line to just fill the graph like so

http://i.imgur.com/OKdjcdU.png?1

VerticalLineAnnotation lineannot = new VerticalLineAnnotation();
lineannot.AnchorDataPoint = chart.Series[item].Points.Last();
lineannot.LineColor = Color.Red;
lineannot.Width = 3;
lineannot.Visible = true;
lineannot.IsInfinitive = true;
chart.Annotations.Add(lineannot);

Solution

  • IsInfinitive is complemented by ClipToChartArea; you can set the line to be clipped to a ChartArea like this:

    lineannot.ClipToChartArea = chart.ChartAreas[item].Name; 
    

    assuming item is the right area name or index.. Note that ClipToChartArea takes the name of the chart area!

    This is the simplest way to do it.

    It is also possible to control an annotation's position and size directly:

    // Note that directly after adding points this will return NaN:
    double maxDataPoint = chart1.ChartAreas[0].AxisY.Maximum;
    double minDataPoint = chart1.ChartAreas[0].AxisY.Minimum;
    
    LineAnnotation annotation2 = new LineAnnotation();
    annotation2.IsSizeAlwaysRelative = false;
    annotation2.AxisX = chart1.ChartAreas[0].AxisX;
    annotation2.AxisY = chart1.ChartAreas[0].AxisY;
    annotation2.AnchorY = minDataPoint;
    annotation2.Height = maxDataPoint - minDataPoint;;
    annotation2.Width = 0;
    annotation2.LineWidth = 2;
    annotation2.StartCap = LineAnchorCapStyle.None;
    annotation2.EndCap = LineAnchorCapStyle.None;
    annotation2.AnchorX = 21;  // <- your point
    annotation2.LineColor = Color.Pink; // <- your color
    chart1.Annotations.Add(annotation2);