I'm using LiveCharts to create a pie chart. I have a list of doubles that I want to represent in the pie chart. The problem is that the values of the list can, and will change, therefore I want to be able to change the chart accordingly.
Here is some sample code from the LiveCharts website:
using System;
using System.Windows.Forms;
using LiveCharts;
using LiveCharts.Wpf;
namespace Winforms.PieChart
{
public partial class PieChartExample : Form
{
public PieChartExample()
{
InitializeComponent();
Func<ChartPoint, string> labelPoint = chartPoint =>
string.Format("{0} ({1:P})", chartPoint.Y, chartPoint.Participation);
pieChart1.Series = new SeriesCollection
{
new PieSeries
{
Title = "Maria",
Values = new ChartValues<double> {3},
PushOut = 15,
DataLabels = true,
LabelPoint = labelPoint
},
new PieSeries
{
Title = "Charles",
Values = new ChartValues<double> {4},
DataLabels = true,
LabelPoint = labelPoint
},
new PieSeries
{
Title = "Frida",
Values = new ChartValues<double> {6},
DataLabels = true,
LabelPoint = labelPoint
},
new PieSeries
{
Title = "Frederic",
Values = new ChartValues<double> {2},
DataLabels = true,
LabelPoint = labelPoint
}
};
pieChart1.LegendLocation = LegendLocation.Bottom;
}
}
}
Essentially, I want to do the same thing, but instead, iterate over the list and create an appropriate number of slices for the pie chart. LiveCharts offers PieSlices
but the PieChart
Control
only accepts a SeriesCollection
, which is why my code crashes when I assign pieChartData
to the chart.
Here is my attempt at filling the PieChart:
LiveCharts.Wpf.PieChart pieChartData = new LiveCharts.Wpf.PieChart();
foreach (var n in areavalues)
{
pieChartData.AddToView(new PieSlice
{
PieceValue = n
});
}
areaChart.Series.Add(new PieSeries(pieChartData)); //<-- CRASH
I'm having a difficult time finding any other example code for LiveCharts, does anyone know how to do this?
This was very helpful. I was having a struggle figuring this out myself until I saw your solution - but it can be much simpler still. In this example, I'm creating a simple, 2 slice %bad pie chart, but it is easy to extend this to any number of slices
1st, define a placeholder pieChart in your Window or UserControl xaml
Then add the slices as PieSeries in your control ctor, with dummy, placeholder values
To update data - simply index into and update the 1st Value in each Series/slice