Friday, May 17, 2024
HomeC#Making a Doughnut Chart for the World's Prime Espresso-Producing Nations

Making a Doughnut Chart for the World’s Prime Espresso-Producing Nations


Welcome to the Chart of the Week weblog collection!

At this time, we are going to visualize the highest coffee-producing international locations worldwide with the assistance of the Syncfusion .NET MAUI doughnut chart. This management is supported on each desktop (Home windows and MacCatalyst) and cell platforms (Android and iOS).

The world espresso manufacturing in 2020 was 5.3 million luggage, decrease than the earlier yr as a consequence of Brazil’s Arabica timber coming into the off yr of their biennial manufacturing cycle.

Check with the next picture, which explains the highest coffee-producing international locations and their manufacturing in 2020.

Visualizing Top Coffee-Producing Countries’ Data Using the Syncfusion .NET MAUI Doughnut Chart

On this weblog, we’ll replicate this chart utilizing the Syncfusion .NET MAUI doughnut chart management.

Step 1: Collect espresso manufacturing knowledge

Earlier than making a chart, we have to collect the information on espresso manufacturing from the Worldwide Espresso Group. For this demonstration, we get hold of knowledge on the international locations concerned, manufacturing quantity in hundreds of thousands, and market share percentages. It can save you the information in CSV format.

Step 2: Put together the information for the doughnut chart

Outline the CoffeeProductionModel class with the properties Nation, Manufacturing, MarketShare, and Index to carry the espresso manufacturing particulars.

Check with the next code instance.

public class CoffeeProductionModel
{
    public string Nation { get; set; }
    public double Manufacturing { get; set; }
    public double MarketShare { get; set; }
    public double Index { get; set; }

    public CoffeeProductionModel(double index, string nation, double manufacturing, double marketShare)
    {
        Index = index;
        Nation = nation;
        Manufacturing = manufacturing;
        MarketShare = marketShare;
    }
}

Subsequent, generate the manufacturing particulars utilizing the WorldCoffeeProduction class and ProductionDetails property. Convert the CSV knowledge to a group of nations and manufacturing quantities utilizing the ReadCSV technique and retailer it within the ProductionDetails property.

Moreover, the choice properties want an interactive characteristic. Within the interactive characteristic part, we are going to cowl extra about this.

Check with the next code instance.

public class WorldCoffeeProduction : INotifyPropertyChanged
{

    Checklist<CoffeeProductionModel> productionDetails;
    public Checklist<Brush> PaletteBrushes { get; set; }
    public Checklist<Brush> SelectionBrushes { get; set; }

    public Checklist<CoffeeProductionModel> ProductionDetails
    {
       get
       {
          return productionDetails;
       }
       set
       {
          productionDetails = worth;
          NotifyPropertyChanged(nameof(ProductionDetails));
       }
    }


    personal Brush selectionBrush;
    public Brush SelectionBrush
    {
        get
        {
           return selectionBrush;
        }
        set
        {
           selectionBrush = worth;

           NotifyPropertyChanged(nameof(SelectionBrush));
        }
    }

    personal string nation;
    public string Nation
    {
       get
       {
          return nation;
       }
       set
       {
                nation = worth;
                NotifyPropertyChanged(nameof(Nation));
       }
    }

    personal double Manufacturing;
    public double Manufacturing
    {
       get
       {
          return manufacturing;
       }
       set
       {
          manufacturing = worth;
          NotifyPropertyChanged(nameof(Manufacturing));
       }
     }

     personal double Share;
     public double Share
     {
        get
        {
           return share;
        }
        set
        {
           share = worth;
           NotifyPropertyChanged(nameof(Share));
        }

      }

      personal int selectedIndex = 0;
      public int SelectedIndex
      {
         get
         {
            return selectedIndex;
         }
         set
         {
            selectedIndex = worth;
            SelectionBrush = SelectionBrushes[SelectedIndex];
            UpdateIndex(worth);
            NotifyPropertyChanged(nameof(SelectedIndex));
          }
       }

       personal double groupTo = 7;
       public double GroupTo
       {
           get { return groupTo; }
           set { groupTo = worth; }
       }

       public WorldCoffeeProduction()
       {
          ProductionDetails = new Checklist<CoffeeProductionModel>(ReadCSV());

          PaletteBrushes = new Checklist<Brush>
          {
              new SolidColorBrush(Shade.FromArgb("#5bdffc")),
              new SolidColorBrush(Shade.FromArgb("#2fe0d0")),
              new SolidColorBrush(Shade.FromArgb("#baf74d")),
              new SolidColorBrush(Shade.FromArgb("#f5d949")),
              new SolidColorBrush(Shade.FromArgb("#f2464d")),
              new SolidColorBrush(Shade.FromArgb("#c86af7"))
           };

           SelectionBrushes = new Checklist<Brush>
           {
              new SolidColorBrush(Shade.FromArgb("#00b1d9")),
              new SolidColorBrush(Shade.FromArgb("#05b3a2")),
              new SolidColorBrush(Shade.FromArgb("#8ccf15")),
              new SolidColorBrush(Shade.FromArgb("#d9b709")),
              new SolidColorBrush(Shade.FromArgb("#d40b13")),
              new SolidColorBrush(Shade.FromArgb("#9e07e3"))
           };
        }

        public IEnumerable<CoffeeProductionModel> ReadCSV()
        {
            Meeting executingAssembly = typeof(App).GetTypeInfo().Meeting;
            Stream inputStream = executingAssembly.GetManifestResourceStream("CoffeeProductionChart.Assets.Uncooked.coffeproductionbycountry.csv");

            string? line;
            Checklist<string> strains = new Checklist<string>();

            utilizing StreamReader reader = new StreamReader(inputStream);
            whereas ((line = reader.ReadLine()) != null)
            {
                strains.Add(line);
            }

            return strains.Choose(line =>
            {
                string[] knowledge = line.Break up(',');
                return new CoffeeProductionModel(Convert.ToDouble(knowledge[0]), knowledge[1], Convert.ToDouble(knowledge[2]), Convert.ToDouble(knowledge[3]));
            });
        }

        personal void UpdateIndex(int worth)
        {
            if (worth >= 0 && worth < ProductionDetails.Rely)
            {
                var mannequin = ProductionDetails[value];
                if (mannequin != null && mannequin.Nation != null)
                {
                    if (mannequin.Manufacturing < GroupTo)
                    {
                        Manufacturing = 0;
                        Share = 0;
                        Nation = "";
                        foreach (var merchandise in productionDetails)
                        {
                            if (GroupTo > merchandise.Manufacturing)
                            {
                                Nation = "Others";
                                Manufacturing += merchandise.Manufacturing;
                                Share += merchandise.MarketShare;
                            }
                        }
                    }
                    else
                    {
                        Nation = mannequin.Nation;
                        Manufacturing = mannequin.Manufacturing;
                        Share = mannequin.MarketShare;
                    }
                }
            }
        }

        public occasion PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
}

Step 3: Configure the Syncfusion .NET MAUI Round Charts

Let’s configure the Syncfusion .NET MAUI Round Charts management.

Check with the next code instance.

<chart:SfCircularChart >
</chart:SfCircularChart>

Step 4: Binding espresso manufacturing knowledge

To bind the espresso manufacturing knowledge, we’ll use the Syncfusion DoughnutSeries class.

<chart:DoughnutSeries  x:Identify="collection" ItemsSource="{Binding ProductionDetails}" XBindingPath="Nation" YBindingPath="Manufacturing">
</chart:DoughnutSeries>

On this instance, we’ve sure the ProductionDetails with the ItemSource property. The XBindingPath and YBindingPath are sure with the Nation and Manufacturing properties, respectively.

Step 5: Customizing the chart look

We are able to customise the doughnut chart’s look by customizing the doughnut phase colours, displaying knowledge labels, including a title to the chart, and extra.

Check with the next code instance to customise the doughnut chart title utilizing the Title property within the SfCircularChart.

<chart:SfCircularChart.Title>
 <Border Background="#443c8f" StrokeThickness="1" Margin="0">
  <VerticalStackLayout>
   <Grid Padding="4">
    <Grid.ColumnDefinitions>
     <ColumnDefinition Width="34"/>
     <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <StackLayout Margin="0,0,0,0" VerticalOptions="Begin" Orientation="Vertical">
     <Path Fill="White" HorizontalOptions="CenterAndExpand" VerticalOptions="Heart" TranslationX="0.5" ScaleY="1.1" TranslationY="0.5" Information="{Binding PathData}"></Path>
    </StackLayout>
    <StackLayout Grid.Column="1" Margin="5,0,0,0"  VerticalOptions="Heart" HorizontalOptions="Begin" Orientation="Vertical">
     <Label  Textual content="The World's Prime Espresso-Producing Nations" FontSize="22"  FontAttributes="Daring" TextColor="white"/>
    </StackLayout>
   </Grid>
  </VerticalStackLayout>
 </Border>
</chart:SfCircularChart.Title>

Let’s configure the chart legend utilizing the ItemTemplate property and place the legend gadgets utilizing the Placement property.

<chart:SfCircularChart.Legend>
 <chart:ChartLegend x:Identify="chartLegend" Placement="Proper" >
  <chart:ChartLegend.ItemTemplate>
   <DataTemplate>
    <StackLayout WidthRequest="{OnPlatform WinUI='150', Android='90',iOS='90',MacCatalyst="140"}" Margin="0,0,80,0" Orientation="Horizontal">
     <Ellipse WidthRequest="15" HeightRequest="15" Fill="{Binding IconBrush}" HorizontalOptions="Heart" VerticalOptions="Heart" />
     <Label FontSize="{OnPlatform WinUI='15', Android='13',MacCatalyst="15",iOS='13'}" Margin="5,0,0,0" FontAttributes="Daring" Textual content="{Binding Merchandise,Converter={StaticResource legend}}" VerticalTextAlignment="Begin"  HorizontalTextAlignment="Begin" />
    </StackLayout>
   </DataTemplate>
  </chart:ChartLegend.ItemTemplate>
 </chart:ChartLegend>
</chart:SfCircularChart.Legend>

Then, we customise the doughnut phase coloration, border, and width and group the information factors lower than the particular worth utilizing the PaletteBrushes, Stroke, StrokeWidth, and GroupTo properties, respectively.

We are able to additionally modify the beginning and finish positions of a phase within the chart utilizing the StartAngle and EndAngle properties.

<chart:DoughnutSeries ShowDataLabels="True" x:Identify="collection" StartAngle="270" EndAngle="630"
           PaletteBrushes="{Binding PaletteBrushes}"
           ItemsSource="{Binding ProductionDetails}" GroupTo="{Binding GroupTo}"      
           XBindingPath="Nation" Stroke="white" StrokeWidth="1"                                    
           YBindingPath="Manufacturing">
</chart:DoughnutSeries>

Configure the CenterView property so as to add details about espresso manufacturing. You may outline the scale of the middle view utilizing the InnerRadius property of the doughnut collection. The CenterHoleSize property is used to stop overlapping among the many doughnut chart segments and heart.

<chart:DoughnutSeries.CenterView>
 <StackLayout x:Identify="format" HeightRequest="{Binding CenterHoleSize}" HorizontalOptions="Heart" VerticalOptions="CenterAndExpand" WidthRequest="{Binding CenterHoleSize}">
  <Label Textual content="P.c of" FontSize="{OnPlatform WinUI='13',Android='9',iOS='10',MacCatalyst="13"}" VerticalTextAlignment="Heart" HorizontalOptions="Heart" VerticalOptions="EndAndExpand" Margin="{OnPlatform WinUI='0',Android='5',MacCatalyst="10",iOS='5'}"/>
  <Label Textual content="Espresso Produced" FontSize="{OnPlatform WinUI='13',Android='9',iOS='10',MacCatalyst="13"}" VerticalOptions="StartAndExpand" Margin="0"  HorizontalOptions="Heart" />
  <Label  Textual content="{Binding Share,Supply={x:Reference coffeeProduction},StringFormat="{0:P0}"}" FontAttributes="Daring" FontSize="{OnPlatform WinUI='15',Android='9',iOS='12',MacCatalyst="14"}" HorizontalOptions="Heart" VerticalOptions="StartAndExpand" Margin="{OnPlatform Android='0',iOS='0',Default="0,-20,0,0"}"/>
 </StackLayout>
</chart:DoughnutSeries.CenterView>

We are able to customise the information labels within the chart utilizing the DataLabelSettings property. Use the LabelPlacement property to position the information labels on the desired place. Modify the label type with an acceptable format utilizing LabelFormat property.

We must always allow the ShowDataLabels property within the doughnut collection to show the information labels.

<chart:DoughnutSeries.DataLabelSettings>
 <chart:CircularDataLabelSettings UseSeriesPalette="True" LabelPlacement="Outer">
  <chart:CircularDataLabelSettings.LabelStyle>
   <chart:ChartDataLabelStyle LabelFormat="###.#M" />
  </chart:CircularDataLabelSettings.LabelStyle>
 </chart:CircularDataLabelSettings>
</chart:DoughnutSeries.DataLabelSettings>

Step 6: Add interactivity characteristic

We are able to add interactive options to view the information for the chosen phase in our chart utilizing the SelectionBehavior property.

The choice options can spotlight a selected knowledge level, increase an occasion, or modify the worth of the SelectedIndex property based mostly on the phase choice. The SelectionBrush property is used to spotlight the chosen phase within the chart.

Right here, we’ll bind the SelectedIndex to the collection heart view to point out further details about the information. Check with the next code instance.

<chart:DoughnutSeries.SelectionBehavior>
 <chart:DataPointSelectionBehavior SelectionBrush="{Binding SelectionBrush}" SelectedIndex="{Binding SelectedIndex,Mode=TwoWay}"  />
</chart:DoughnutSeries.SelectionBehavior>

After executing the earlier code instance, we’ll get output like within the following picture.

Visualizing Top Coffee-Producing Countries’ Data Using the Syncfusion .NET MAUI Doughnut Chart
Visualizing Prime Espresso-Producing Nations’ Information Utilizing the Syncfusion .NET MAUI Doughnut Chart

GitHub reference

For extra particulars, check with the GitHub demo.

Conclusion

Thanks for studying! On this weblog, we’ve seen tips on how to visualize the world’s high coffee-producing international locations utilizing the Syncfusion .NET MAUI doughnut chart. Like this, it’s also possible to visualize different traits and adjustments worldwide. We encourage you to strive the steps mentioned and share your ideas within the feedback part under.

It’s also possible to attain us through our help discussion boardhelp portal, or suggestions portal. We’re at all times keen that will help you!

Associated blogs

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments