简体   繁体   中英

Auto format DateTime axis for MS chart control?

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?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM