Search code examples
c#mschart

How to show only one dashed line for Y axis at center in Microsoft chart controls?


I want to display a single dashed line along Y-axis positioned at the middle vertically. I thought of it as a trivial problem but it seems that either I don't know how to do it or it is not available as a direct option.

This is what I've tried so far

chart1.ChartAreas[0].AxisY.Enabled = AxisEnabled.True;
chart1.ChartAreas[0].AxisY.LineWidth = 1;
chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = true;
chart1.ChartAreas[0].AxisY.MinorGrid.Enabled = false;

chart1.ChartAreas[0].AxisY.IsStartedFromZero = true;

chart1.ChartAreas[0].AxisY.MajorGrid.IntervalType = DateTimeIntervalType.Number;
chart1.ChartAreas[0].AxisY.MajorGrid.IntervalOffsetType = DateTimeIntervalType.Number;
chart1.ChartAreas[0].AxisY.MajorGrid.Interval = 5;
chart1.ChartAreas[0].AxisY.Interval = 5;    

chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.Black;
chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dash;

Note that I know interval property is not set according to what I want but the problem is no matter what value I set for chart1.ChartAreas[0].AxisY.Interval property chart control simply draws so many lines along Y-axis. I'd even tried normalizing my input to the range [-50, 50] and rounded them to integers but still the results are same. However, my logic of interval is working with X-axis and yielding expected results but not for Y-axes.


Solution

  • So I got the solution based on the example provided by TaW. Pasting here the example code I used, may it help someone.

    ChartArea CA = chart1.ChartAreas[0];
            Series S1 = chart1.Series[0];
            S1.ChartType = SeriesChartType.Line;
            CA.AxisY.Maximum = 100;
            CA.AxisY.Minimum = -100;
    
            CA.AxisY.Crossing = 0;
    
            CA.AxisY.Interval = 10;
    
            CA.AxisY.LineWidth = 1;
    
            CA.AxisY.MajorGrid.Enabled = false;
            CA.AxisY.MinorTickMark.Enabled = false;
    

    The trick was to disable gridlines and show a line at the middle by setting Crossing = 0 as suggested by TaW. Note that it's only for Y-axis if anyone wants to have it for both axis than need to apply the same properties to X-axis.