Search code examples
c#chartsdotnetcharting

Remove extra x axis values


I'm having trouble removing extra values in the x column. Basically, my graph doesn't start at 0, nor does it end at my last data point. I have tried starting the axis at 0, as well as setting the interval offset to -20 (my interval is 20).

Is there any way i can get rid of the extra values on either side of my data?

string[] xValues = new string[5] { "QE1", "QE2", "QE3", "QE4", $"{DateTime.Now.ToShortDateString()}" };

        PlotBaselines(xValues);

        var amCost = new Series()
        {
            Name = "AmCost",
            Color = Color.Blue,
            IsVisibleInLegend = true,
            IsXValueIndexed = true,
            ChartType = SeriesChartType.Line
        };
        impairmentGraph.Series.Add(amCost);
        // Test Values 0 - 20
        float[] amCostValues = new float[5] { 5, 15, 20, 13, 6 };
        impairmentGraph.Series["AmCost"].Points.DataBindXY(xValues, amCostValues);

Here is the code for a series. Each is the same.

impairmentGraph.ChartAreas[0].AxisY.Maximum = 100; impairmentGraph.ChartAreas[0].AxisY.Interval = 20; impairmentGraph.ChartAreas[0].AxisX.IntervalOffset = -20; impairmentGraph.ChartAreas[0].AxisX.IsStartedFromZero = true;

Here is the only set up code I'm using.

Picture illustrating my issue


Solution

  • You need to set the Minimum and Maximum of your x-axis.

    But: This can only work if you have added the x-values as numbers ( or datetimes) ! Yours are not!

    Here are changes that will help:

    Change the xvalues to numbers:

     double[] xValues = new double[5] {  1,2,3,4,5 };
    

    Put your labels in another array:

     string[] xLabels = new string[5] { "QE1", "QE2", "QE3", "QE4", 
                                        $"{DateTime.Now.ToShortDateString()}" };
    

    After binding the data you need to set the AxisLabels for the DataPoints:

     for (int i = 0; i < xValues.Length; i++)
                impairmentGraph.Series["AmCost"].Points[i].AxisLabel = xLabels[i];
    

    Now you can set the range the x-axis shall display:

     impairmentGraph.ChartAreas[0].AxisX.Minimum = 1;
     impairmentGraph.ChartAreas[0].AxisX.Maximum = 5;
    

    With my data the result looks like this:

    enter image description here

    Note that when you add x-values as string they will all be converted to double resulting in a values of 0.0d for all points. (Do check this in the debugger!!) Therefore you can't use them anymore for anything at all; not for setting the range nor for formatting the labels or for feeding Tooltips etc..

    The fact that the strings are first fed into the AxisLabels misleads many folks to assume that all is well, it isn't..

    Also note that I always chose List over arrays and that this rather fixed set of data doesn't reall profit from databinding, especially since we need to access each DataPoint anyway..