Juan Nevarez
Juan Nevarez

Reputation: 3

How to chart a list of N items using microcharts xamarin forms

Im trying to make a chart in xamarin forms using xaml, and i want to chart a list of "n" items, but, it only displays the last item of the list, it seems that the data in the entry is erased and replaced evry time the foreEach cicle finishes.

this is the code

if (ID != "")
{
    Empresa empresa = App.BD.ObtenerEmpresa(ID);
    var reportes = App.BD.ObtenerReportes(ID);

    foreach (var CurrentData in reportes)
    {
        var random = new Random();
        var color = String.Format("#{0:X6}", random.Next(0x1000000));
        var entries = new[]
        {
            new Entry(float.Parse(CurrentData.Mejora))
            {
                Label = CurrentData.FechaReporte.ToString(),
                Color = SKColor.Parse(color),
                ValueLabel = CurrentData.Mejora
            }
        };

        chart1.Chart = new DonutChart() { Entries = entries };
    }
}

Upvotes: 0

Views: 1223

Answers (1)

Xiaoy312
Xiaoy312

Reputation: 14487

You are creating a new chart for every item, that is why you only get the last item.

What you should is to move the entry chart out of the for-loop, and create it once with all the entries:

if (ID != "")
{
    Empresa empresa = App.BD.ObtenerEmpresa(ID);
    var reportes = App.BD.ObtenerReportes(ID);
    var random = new Random();

    chart1.Chart = new DonutChart()
    {
        Entries = reportes
            .Select(x => new Entry(float.Parse(x.Mejora))
            {
                Label = x.FechaReporte.ToString(),
                Color = SKColor.Parse($"#{random.Next(0x1000000):X6}"),
                ValueLabel = x.Mejora
            })
            .ToArray()
    };
}

Here is a simpler version to help you understand: (both are equivalent)

if (ID != "")
{
    Empresa empresa = App.BD.ObtenerEmpresa(ID);
    var reportes = App.BD.ObtenerReportes(ID);

    var random = new Random();
    var entries = new List<Entry>();
    foreach (var CurrentData in reportes)
    {
        var color = String.Format("#{0:X6}", random.Next(0x1000000));

        entries.Add(new Entry(float.Parse(CurrentData.Mejora))
        {
            Label = CurrentData.FechaReporte.ToString(),
            Color = SKColor.Parse(color),
            ValueLabel = CurrentData.Mejora
        });
    }

    chart1.Chart = new DonutChart() { Entries = entries };
}

note: you should also reuse the same Random, instead of creating a new one every time you need it.

Upvotes: 3

Related Questions