Search code examples
winformscharts

Only integer labels in X-Axis Winforms Chart


I'm writing a calculation application in WinForms. At the end, a graph is generated. Unfortunately, I can not do that so that the labels on the X axis are only integers, and thus that the vertical lines on the graph also correspond to the integer values.

Values on the X axis are double values, I want them to be between integers.

for (int i = 0; i < _results.Bests.Count; i++)
{
    resChart.Series["Best"].Points.AddXY(i, _results.Bests[i]);
    var resval = _results.ResValues[i];
    int count = 1;
    foreach (var elem in resval)
    {
        double xVal = i + (1.0 / resval.Count) * count;
        resChart.Series["Results"].Points.AddXY(xVal, elem);
        count++;
        }
}

To sum up, on the graph I have labels on the X axis, e.g. 0.3333, 1.3333, 2.3333 and I want them to be 1, 2, 3, etc.


Solution

  • Assuming you are using the DataVisiualization.Charting classes, you can manipulate the axis via:

    resChart.ChartAreas[0].AxisX
    

    One of the axis options is:

    resChart.ChartAreas[0].AxisX.RoundAxisValues();
    

    which might be exactly what you want.

    https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datavisualization.charting.axis?view=netframework-4.8