0

I'm using the MS chart control to display a time series. Points are added to the series over time, and the user can zoom in/out using the normal built-in controls.

The question is, how can I set it up so that the X-axis labels automatically show a format that's appropriate for the time range being displayed?

For example, when the time range displayed on the chart is < 1 hour, I'd want to set it to display HH:mm:ss:

ChartAreas[0].AxisX.LabelStyle.Format ="HH:mm:ss";    

But if I zoom out on the same chart to show 6 days of data, I'd want it to display just the date:

ChartAreas[0].AxisX.LabelStyle.Format ="dd/MM/yy";

Is there any built-in functionality to do this?

2 Answers 2

2
+50

You can hook into the Chart.AxisViewChanged event (assuming you're using the built-in zooming functionality of the chart), and set the format based on the axis range:

private void Chart_AxisViewChanged(object sender, ViewEventArgs e)
{
    DateTime range = ChartAreas[0].AxisX.ScaleView.ViewMaximum - ChartAreas[0].AxisX.ScaleView.ViewMinimum;
    if (range > 6 days)
    {
        ChartAreas[0].AxisX.LabelStyle.Format = "dd/MM/yy";
    }
    else
    {
        ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
    }
}

You can of course make that if statement more complicated to handle more cases as desired.

Sign up to request clarification or add additional context in comments.

1 Comment

ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss" does not work for me and show "HH:mm:ss" instead of x axis label such as "00:12:45". Is this a version problem?
0

By using the AxisViewChanged event you can catch the user zooming on your graph:

Occurs when the axis scale view position or size is changed.

For example here is one implementation where the format changes depending on the zoom leve. Very naive implementation, since the NewSize property can be NaN but it can give you the right direction

private void chart1_AxisViewChanged(object sender, ViewEventArgs e)
{
    var format = "{0.".PadRight(Convert.ToInt32(3 + e.NewSize), '0') + "}";

    e.Axis.LabelStyle.Format = format;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.