Reputation: 3214
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?
Upvotes: 0
Views: 2400
Reputation: 14962
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;
}
Upvotes: 0
Reputation: 1610
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.
Upvotes: 2