问题
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?
回答1:
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
numbersorDateTimes. If you added them asstringsthey all are0and indexing makes no sense.that the
DataPointswere added in ascending order. This is not always the case, especially when plottingLineCharts. 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;
来源:https://stackoverflow.com/questions/38663244/how-to-align-indexed-series-in-a-chart