When setting a Series
to be indexed by setting the Series.IsXValueIndexed
to true
the chart requires all Series
to be aligned:
If you are displaying multiple series and at least one series uses
indexed X-values, then all series must be aligned — that is, have the
same number of data points—and the corresponding points must have the
same X-values.
How can you add the necessary Emtpy DataPoints
to the slots they are missing in, in any of the Series
?
This routine first collects all values in all Series
in a collection of doubles
.
Then it loops over all Series
and over all values and inserts the missing empty DataPoints
:
void AlignSeries(Chart chart)
{
var allValues = chart.Series.SelectMany(s => s.Points)
.Select(x=>x.XValue).Distinct().ToList();
foreach (Series series in chart.Series)
{
int px = 0; //insertion index
foreach(double d in allValues )
{
var p = series.Points.FirstOrDefault(x=> x.XValue == d);
if (p == null) // this value is missing
{
DataPoint dp = new DataPoint(d, double.NaN);
dp.IsEmpty = true;
series.Points.Insert(px, dp);
}
px++;
}
}
}
Note that the code assumes ..
that your x-values are correctly set, i.e. they were added as numbers
or DateTimes
. If you added them as strings
they all are 0
and indexing makes no sense.
that the DataPoints
were added in ascending order. This is not always the case, especially when plotting LineCharts
. However indexing these makes no sense either.
Also note that you can set several options of how to treat Empty DataPoints
in a Series
by setting properties in the Series.EmptyPointStyle
, which is derived from DataPointCustomProperties
.
So you could set their Color
like this:
someSeries.EmptyPointStyle.Color = Color.Red;