Studley
Studley

Reputation: 63

How to display C# winforms chart x axis labels in descending order

I have a chart which is populated with DateTime values in descending order, but the x axis labels are in ascending order. How do I get the labels to match the data?

foreach (var eventData in eventResultsFinal) 
{
    sensorTimeStamp = ConvertFromUnixTimestamp(secondsSinceEpoch + 
                      Convert.ToInt32(eventData.t1)); 
    if (eventData.v1.Equals("active")) 
        chart1.Series[chartSeriesCounter].Points
              .AddXY(sensorTimeStamp.ToOADate(), 1 + yOffset); 
    else if (eventData.v1.Equals("inactive")) 
        chart1.Series[chartSeriesCounter].Points
              .AddXY(sensorTimeStamp.ToOADate(), 0 + yOffset); 
    }
}

enter image description here

See the image above - the timestamps are increasing, I would like them decreasing.

Upvotes: 1

Views: 1605

Answers (1)

TaW
TaW

Reputation: 54433

If you want to show the data in a reversed order you can tell the X-axis to do so by setting its IsReversed property:

  chart1.ChartAreas[0].AxisX.IsReversed;

An alternative, but not recommended way would be to add the X-Values as strings instead of DateTimes. Then the DataPoints would be ordered in the same way you add them, but you could not really work with the X-values anymore..

Update: Since Reversing the X-Axis also reverses the order of the Y-Axis placement you may want to set the Y-Axes like this:

chart1.ChartAreas[0].AxisY.Enabled = AxisEnabled.False;
chart1.ChartAreas[0].AxisY2.Enabled = AxisEnabled.True;

Note: All styling of the primary Y-Axis should now go to the secondary one (AxisY2), including any CustomLabels.

Upvotes: 1

Related Questions