Reputation: 69
I'm trying to label my pie chart with the name of the column value (which in this case would be the machine name, and the percentage next to it. This is quite difficult by default in c#. I'm taking data from a MySql database and plotting it based on the column "machine". Below is the code I currently have which will only displays the percentage:
string DatabaseCountMachines = "SELECT Machine, COUNT(*) total FROM completed GROUP BY Machine";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(DatabaseCountMachines, conDataBase);
MySqlDataReader StatsbyMachine;
try
{
conDataBase.Open();
StatsbyMachine = cmdDataBase.ExecuteReader();
while (StatsbyMachine.Read())
{
this.chartMachine.Series["Series1"].Points.AddXY(StatsbyMachine.GetString("Machine"), StatsbyMachine.GetString("total"));
this.chartMachine.Series["Series1"].CustomProperties = "PieLabelStyle=Outside";
this.chartMachine.Series["Series1"].Label = "#LEGENDTEXT" + "#PERCENT";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Upvotes: 1
Views: 3861
Reputation: 54433
In a Pie Chart the x-values
do not apply so they don't show... You might as well use AddY
.
Simply add both data to the Label
of each DataPoint
!
Change
chartMachine.Series["Series1"].Points
.AddXY(StatsbyMachine.GetString("Machine"), StatsbyMachine.GetString("total"));
to
int index = chartMachine.Series["Series1"].Points.AddY(StatsbyMachine.GetString("total"));
chartMachine.Series["Series1"].Points[index].Label =
StatsbyMachine.GetString("Machine") + " : " + StatsbyMachine.GetString("total");
Do note that while the strings you add as y-values will get converted to numbers this would not apply to x-values even if you use a chart type that uses x-values.
Some chart data do not need numeric x-values, like Names, Cities or even IDs so the will not be automatically converted, even where they could be.
Y-values otoh always need to be numeric or else the whole idea of charting makes no sense. Therefore your string total
will be converted to numbers, if at all possible. Where the conversion fails the values will be 0
..
Upvotes: 2