The example sorts X-axis data by totals in a WinForms Chart.
In this example, the X-axis displays qualitative values. These values do not have an inherent numeric order - they are plotted in the same order as series points in the collection. The example assigns a custom comparer to the AxisBase.QualitativeScaleComparer property to sort string values in a custom order: the comparer calculates the total value for each stacked bar and sorts stacked bars by aggregated values.
This example binds the ChartControl
to a data source created in code. It generates three series, each with ten arguments and random values. To sort stacked bars by their aggregate values (totals), do the following:
Create a ArgumentByTotalComparer
class (based on IComparer). The comparer sorts arguments based on their total values stored in a dictionary:
class ArgumentByTotalComparer : IComparer {
Dictionary<string, double> argTotalDict;
public ArgumentByTotalComparer(Dictionary<string, double> argTotalDict) {
this.argTotalDict = argTotalDict;
}
public int Compare(object x, object y) {
return argTotalDict[(string)x].CompareTo(argTotalDict[(string)y]);
}
}
The GetTotalByArg
method calculates the sum (the total) for a stacked bar.
double GetTotalByArg(object arg) {
double total = 0;
foreach (Series series in chartControl1.Series)
foreach (SeriesPoint point in series.Points)
if (Equals(point.Argument, arg))
total += point.Values[0];
return total;
}
Handle the ChartControl.BoundDataChanged event. This event fires after the chart is bound to the data source and generates series points. In the event handler, you can calculate totals and other aggregations based on the loaded chart data.
In the event handler, do the following:
- Call the
GetTotalByArg
method for each argument from the series point to create a new dictionary with totals based on chart values. - Pass the created dictionary as a parameter for the
ArgumentByTotalComparer
constructor. - Assign the comparer to the chart's qualitative axis (AxisBase.QualitativeScaleComparer).
public partial class Form1 : Form {
// ...
void ChartControl1_BoundDataChanged(object sender, EventArgs e) {
Series series = chartControl1.Series[0];
var argTotalDict = new Dictionary<string, double>();
for (int i = 0; i < ArgumentNumber; i++) {
string argument = series.Points[i].Argument;
double total = GetTotalByArg(argument);
argTotalDict.Add(argument, total);
}
AxisX axisX = ((XYDiagram)chartControl1.Diagram).AxisX;
axisX.QualitativeScaleComparer = new ArgumentByTotalComparer(argTotalDict);
}
}
- AxisBase.QualitativeScaleComparer
- ChartControl.BoundDataChanged
- Charts - Sorting Data
- Reorder Qualitative Axis Values
(you will be redirected to DevExpress.com to submit your response)