Search code examples
c#winformschartspoint

How to create a line from (0,0) to (0,n) in WinForms chart?


I tried to draw a line from (0,0) to (0,3) using Winforms chart, but it is drawing a line from (1,0) to (2,3). The same thing happens with any other Y value of the second point.

public partial class Form1 : Form
{
    private Series series = new Series("series")
    {
        ChartType = SeriesChartType.Line,
        Color = Color.Red
    };
    public Form1()
    {
        InitializeComponent();
        series.Points.AddXY(0, 0);
        series.Points.AddXY(0, 3);
        chart1.Series.Add(series);
        chart1.ChartAreas[0].AxisX.Minimum = -2;
        chart1.ChartAreas[0].AxisX.Maximum = 5;
        chart1.ChartAreas[0].AxisY.Minimum = -2;
        chart1.ChartAreas[0].AxisX.Maximum = 5;
        chart1.ChartAreas[0].AxisX.Interval = 1;
        chart1.ChartAreas[0].AxisY.Interval = 1;

    }
}

chart snapshot

When I was trying to create a line from (0,0) to (2,3) everything was okay.

chart snapshot

How to fix it and what's the cause?


Solution

  • From what I can tell, when all X values are 0, the chart does not respect value of 0 and thus starts treating your series as though you indented the index of the data point to be your X value.

    adding a second series with at least 1 data point that has a non-0 X, will correct the problem.

    public partial class Form1 : Form
    {
        private Series series = new Series("series")
        {
            ChartType = SeriesChartType.Line,
            Color = Color.Red
        };
        private Series correction = new Series("correction")
        {
            ChartType = SeriesChartType.Line,
            Color = Color.Transparent,
            IsVisibleInLegend = false,
            IsValueShownAsLabel = false,
        };
        public Form1()
        {
            InitializeComponent();
    
            series.Points.AddXY(0, 0);
            series.Points.AddXY(0, 3);
    
            chart1.Series.Add(series);
    
            correction.Points.AddXY(1, 1);
            chart1.Series.Add(correction);
    
        }
    }