murf
murf

Reputation: 374

How to keep labels at multiples of e.g. 5 for a scrolling chart

I have a winforms chart which is bound to a List. Every two seconds a new measurement is added to the list. My program is zooming to a 25 second interval and then scrolling to the end of the chart. I would like the x-axis to show multiples of 5 (5, 10, 15, 20...).

chart with rounded labels

In the beginning it works fine, but then when the chart grows bigger and scrolling begins the labels, ticks and gridlines shift (e.g. 23, 28, 33, 38...).

enter image description here

How do I change this so it shows 25, 30, 35, 40... instead?

Here is my code for the chart:

chartArea1.AxisX.LabelStyle.Interval = 5D;
chartArea1.AxisX.MajorGrid.Interval = 5D;
chartArea1.AxisX.MajorTickMark.Interval = 5D;
chartArea1.AxisX.Minimum = 0D;
chartArea1.AxisX.MinorGrid.Interval = 5D;
chartArea1.AxisX.ScaleView.Position = 0D;
chartArea1.AxisX.ScaleView.Size = 25D;
chartArea1.AxisX.ScrollBar.Enabled = false;
chartArea1.AxisX.Title = "Time [s]";
chartArea1.AxisY.Interval = 20D;
chartArea1.AxisY.Title = "Cold pump\\nVol. [ml]";
chartArea1.Name = "ChartColdPump";
chartArea1.Position.Auto = false;
chartArea1.Position.Height = 25F;
chartArea1.Position.Width = 99F;

And the code for the scrolling, called each time a new measurement is added to the list:

componentsChart.ChartAreas[0].AxisX.ScaleView.Scroll(ScrollType.Last);

Upvotes: 2

Views: 538

Answers (1)

TaW
TaW

Reputation: 54433

You need to adapt the various interval offsets to keep the labels at multiples of 5 or any other Interval you want.

Here is an example:

Axis ax = componentsChart.ChartAreas[0].AxisX; ;

ax.ScaleView.Scroll(ScrollType.Last);

int i1     = (int)ax.ScaleView.Position - 1;  // by default labels start at 1
int mult   = (int)ax.LabelStyle.Interval;
int offset = i1 % mult  == 0 ? 0 : mult  - (i1 % mult );

ax.IntervalOffset = offset;
ax.MajorGrid.IntervalOffset = offset;

Note that the default label start is at 1; you override it by setting a Minimum but after scrolling this no longer holds. So we need an offset to shift the intervals by the right amount..

enter image description here

Upvotes: 1

Related Questions