core114
core114

Reputation: 5335

Blazorise Pie chart component

Im beginner with Blazorise and im using Blazorise Chart component, but I'm looking for implement Blazorise Pie chart component, dose any idea s for how to implement this. there is no example

Upvotes: 0

Views: 936

Answers (1)

Dimitris Maragkos
Dimitris Maragkos

Reputation: 11392

You can try this as a starting example and modify according to your application:

<Chart @ref="pieChart" Type="ChartType.Pie" TItem="double" Options="@chartOptions" />
<Button Color="Color.Primary" Outline Clicked="@(async () => await HandleRedraw( pieChart, GetPieChartDataset ))">Redraw</Button>

@code {
    private Chart<double> pieChart;

    ChartOptions chartOptions = new() { AspectRatio = 1.5 };

    private string[] Labels = { "Red", "Blue", "Yellow", "Green", "Purple", "Orange" };
    private List<string> backgroundColors = new() { ChartColor.FromRgba(255, 99, 132, 0.2f), ChartColor.FromRgba(54, 162, 235, 0.2f), ChartColor.FromRgba(255, 206, 86, 0.2f), ChartColor.FromRgba(75, 192, 192, 0.2f), ChartColor.FromRgba(153, 102, 255, 0.2f), ChartColor.FromRgba(255, 159, 64, 0.2f) };
    private List<string> borderColors = new() { ChartColor.FromRgba(255, 99, 132, 1f), ChartColor.FromRgba(54, 162, 235, 1f), ChartColor.FromRgba(255, 206, 86, 1f), ChartColor.FromRgba(75, 192, 192, 1f), ChartColor.FromRgba(153, 102, 255, 1f), ChartColor.FromRgba(255, 159, 64, 1f) };
  
    private bool isAlreadyInitialised;

    private Random random = new(DateTime.Now.Millisecond);
  
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!isAlreadyInitialised)
        {
            isAlreadyInitialised = true;

            await HandleRedraw(pieChart, GetPieChartDataset);
        }
    }

    private async Task HandleRedraw<TDataSet, TItem, TOptions, TModel>(Blazorise.Charts.BaseChart<TDataSet, TItem, TOptions, TModel> chart, Func<TDataSet> getDataSet)
        where TDataSet : ChartDataset<TItem>
        where TOptions : ChartOptions
        where TModel : ChartModel
    {
        await chart.Clear();

        await chart.AddLabelsDatasetsAndUpdate(Labels, getDataSet());
    }
    
    private int pieLabel;

    private PieChartDataset<double> GetPieChartDataset()
    {
        return new()
        {
            Label = $"#{++pieLabel} of randoms",
            Data = RandomizeData(),
            BackgroundColor = backgroundColors,
            BorderColor = borderColors,
            BorderWidth = 1
        };
    }

    List<double> RandomizeData() => RandomizeData(3, 50);

    List<double> RandomizeData(int min, int max)
    {
        return Enumerable.Range(0, 6).Select(x => random.Next(min, max) * random.NextDouble()).ToList();
    }
}

You can find more examples for all Blazorise components in Blazorise.Demo project which you can find at GitHub: https://github.com/Megabit/Blazorise/tree/master/Demos/Blazorise.Demo/Pages/Tests

Upvotes: 1

Related Questions