Reputation: 31
I am generating pie charts by pulling data from SQL tables. The data is an accumulation of hours for different projects.
The charts are building fine but I would like the pie graph to display the respective percentage of each slice of the pie that is being used when the graphs are generated.
I am creating the charts in the method shown below.
// Fill Chart with usable data
for (int i = 0; i <= index - 1; i++)
{
Chart6.Series["Series1"].Points.AddXY(project[i], projTime[i]);
}
Chart6.Series[0]["PieLabelStyle"] = "Disabled";
I was hoping there would be a simple command I could pass in the code behind to create this but scouring the web has provided no usable results. The best I have found is this method but these are not options in Visual Studio Express 2013.
Upvotes: 2
Views: 4099
Reputation: 54453
Prepare like this:
Series S = Chart6.Series["Series1"];
S.ChartType = SeriesChartType.Pie;
S.IsValueShownAsLabel = true;
S["PieLabelStyle"] = "Outside";
Create DataPoints like this if you know the total:
DataPoint p = new DataPoint(project[i], projTime[i]);
// check your data type for the calculation!
p.Label = p.YValues[0] + "h =\n" +
(100d * p.YValues[0] / total).ToString("00.00") + "%\n"; // my format
If you don't know the total, first set the points, then calculate the total and finally set the label:
for (int i = 0; i <= index - 1; i++)
{
S.Points.AddXY(project[i], projTime[i]);
}
// calculate the total:
double total = S.Points.Sum(dp => dp.YValues[0]);
// now we can set the percentages
foreach (DataPoint p in S.Points)
{
p.Label = p.YValues[0] + "h =\n" +
(100d * p.YValues[0] / total).ToString("00.00") + "%\n"; // my format
}
chart1.Titles.Add(S.Points.Count + " projects, total " +
total.ToString("###,##0") + " hours");
chart1.Titles[0].Font = new System.Drawing.Font("Arial", 14f);
Upvotes: 2