Monday, July 15, 2024
HomeC#Making a .NET MAUI Doughnut Chart to Visualize the World's Greatest Oil...

Making a .NET MAUI Doughnut Chart to Visualize the World’s Greatest Oil Producers


TL;DR: Let’s craft a .NET MAUI Doughnut Chart to visualise the 2023 oil manufacturing knowledge. We cowl knowledge preparation, chart configuration, and customization steps to create an interactive and visually interesting chart.

Welcome to our Chart of the Week weblog sequence!

At the moment, we’ll visualize the world’s largest oil producers in 2023 utilizing Syncfusion’s .NET MAUI Doughnut Chart.

Regardless of ongoing efforts to decarbonize the worldwide economic system, oil stays one of many world’s most important assets. It’s produced by a comparatively small group of nations, granting them vital financial and political leverage.

This graphic illustrates international crude oil manufacturing in 2023, measured in million barrels per day, sourced from the U.S. Power Data Administration (EIA).

The next picture exhibits the Doughnut Chart we’re going to create. 

Visualizing the world’s biggest oil producers’ data using the Syncfusion .NET MAUI Doughnut Chart

Let’s get began!

Step 1: Collect oil manufacturing knowledge 

Earlier than creating the .NET MAUI Doughnut Chart, we have to collect knowledge from the U.S. Power Data Administration (EIA). We will additionally obtain the info in CSV format. 

Step 2: Put together the info for the Doughnut Chart

Then, we have to set up our knowledge correctly. This entails creating an OilProductionModel class, which defines the construction of our oil manufacturing knowledge, and a WorldOilProduction class, which handles the info manipulation and communication between the mannequin and the Doughnut Chart.

The info mannequin represents the info we need to visualize. It may include the properties to retailer the small print such because the nation title, oil manufacturing worth, and nation flag picture.

public class OilProductionModel
{
        public string Nation { get; set; }
        public double Manufacturing { get; set; }
        public string FlagImage { get; set; }
        public OilProductionModel(string nation, double manufacturing, string flagImage)
        {
            Nation = nation;
            Manufacturing = manufacturing;
            FlagImage = flagImage;
        }
}

Now, create the WorldOilProduction class, which acts as an middleman between the info fashions and the consumer interface components (Doughnut Chart), making ready and formatting knowledge for show and interplay.

Moreover, we have to configure the properties to replace the exploding phase values within the heart view labels.

public class WorldOilProduction : INotifyPropertyChanged
{
    public Checklist<OilProductionModel> ProductionDetails { get; set; }
    public Checklist<Brush> PaletteBrushes { get; set; }
    personal double productionValue;
    public double ProductionValue
    {
        get
        {
            return productionValue;
        }
        set
        {
            productionValue = worth;
            NotifyPropertyChanged(nameof(ProductionValue));
        }
    }
    personal string countryName;
    public string CountryName
    {
        get
        {
            return countryName;
        }
        set
        {
            countryName = worth;
            NotifyPropertyChanged(nameof(CountryName));
        }
    }
    int explodeIndex = 1;
    public int ExplodeIndex
    {
        get
        {
            return explodeIndex;
        }
        set
        {
            explodeIndex = worth;
            UpdateIndexValues(worth);
            NotifyPropertyChanged(nameof(ExplodeIndex));
        }
    }
    public WorldOilProduction()
    {
        ProductionDetails = new Checklist<OilProductionModel>(ReadCSV());
        PaletteBrushes = new Checklist<Brush>
        {
            new SolidColorBrush(Coloration.FromArgb("#583101")),
            new SolidColorBrush(Coloration.FromArgb("#603808")),
            new SolidColorBrush(Coloration.FromArgb("#6f4518")),
            new SolidColorBrush(Coloration.FromArgb("#8b5e34")),
            new SolidColorBrush(Coloration.FromArgb("#a47148")),
            new SolidColorBrush(Coloration.FromArgb("#bc8a5f")),
            new SolidColorBrush(Coloration.FromArgb("#d4a276")),
            new SolidColorBrush(Coloration.FromArgb("#e7bc91")),
            new SolidColorBrush(Coloration.FromArgb("#f3d5b5")),
            new SolidColorBrush(Coloration.FromArgb("#FFEDD8"))
        };
    }
    public occasion PropertyChangedEventHandler PropertyChanged;
    public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    personal void UpdateIndexValues(int worth)
    {
        if (worth >= 0 && worth < ProductionDetails.Rely)
        {
            var mannequin = ProductionDetails[value];
            if (mannequin != null && mannequin.Nation != null)
            {
                ProductionValue = mannequin.Manufacturing;
                CountryName = mannequin.Nation;
            }
        }        
    }
}

Then, convert the CSV knowledge into a knowledge assortment utilizing the ReadCSV technique. 

public IEnumerable<OilProductionModel> ReadCSV()
{
     Meeting executingAssembly = typeof(App).GetTypeInfo().Meeting;
     Stream inputStream = executingAssembly.GetManifestResourceStream("OilProductionChart.Assets.Uncooked.knowledge.csv");
     string? line;
     Checklist<string> traces = new Checklist<string>();
     utilizing StreamReader reader = new StreamReader(inputStream);
     whereas ((line = reader.ReadLine()) != null)
     {
        traces.Add(line);
     }
     return traces.Choose(line =>
     {
        string[] knowledge = line.Break up(',');
        return new OilProductionModel(knowledge[1], Convert.ToDouble(knowledge[2]), knowledge[3]);
     });
}

Step 3: Configure the Syncfusion .NET MAUI Doughnut Chart

Let’s configure the .NET MAUI Doughnut Chart management utilizing this documentation.

Seek advice from the next code instance.

<ContentPage
    . . .
    xmlns:chart="clr-namespace:Syncfusion.Maui.Charts;meeting=Syncfusion.Maui.Charts">
    <chart:SfCircularChart>
       . . .
        <chart:DoughnutSeries>
            . . .
        </chart:DoughnutSeries>
    </chart:SfCircularChart>
</ContentPage>

Step 4: Bind the info to .NET MAUI Doughnut Collection

To successfully show the oil manufacturing knowledge, we’ll use the Syncfusion DoughnutSeries occasion and bind our ProductionDetails assortment to the chart.

Seek advice from the next code instance. 

<chart:SfCircularChart>
   . . .
    <chart:DoughnutSeries ItemsSource="{Binding ProductionDetails}" 
                          XBindingPath="Nation" 
                          YBindingPath="Manufacturing"/>
</chart:SfCircularChart>

Within the above code, the ProductionDetails assortment from the WorldOilProduction ViewModel is certain to the ItemSource property. The XBindingPath and YBindingPath properties are certain to the Nation and Manufacturing properties, respectively.

Step 5: Customise the .NET MAUI Doughnut Chart look

Let’s customise the looks of the .NET MAUI Doughnut Chart to reinforce its readability.

Including the chart title

Including a Title helps customers perceive the content material of the chart extra successfully. Seek advice from the next code instance to customise the chart title.

<chart:SfCircularChart.Title>
    <Grid Margin="4,5,0,0" >
        <Grid.RowDefinitions>
            <RowDefinition Top="80"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="55"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Picture Grid.Column="0" 
                Grid.RowSpan="2" 
                Supply="oil.png" 
                Margin="0,-5,0,0" 
                HeightRequest="60" 
                WidthRequest="60"/>
        <StackLayout Grid.Column="1" Grid.Row="0" Margin="0,10,0,0">
            <Label Textual content="The World's Greatest Oil Producers in 2023"   
                    Margin="0,0,0,6"
                    FontSize="22"    
                    FontFamily="centurygothic"
                    FontAttributes="Daring"  
                    TextColor="Black"/>
            <Label Textual content="Crude Oil Manufacturing (Million barrels per day)"   
                    FontSize="18"      
                    FontFamily="centurygothic"
                    TextColor="Black"  
                    Margin="0,2,0,0"/>
        </StackLayout>
    </Grid>
</chart:SfCircularChart.Title>

Customise the doughnut sequence

Seek advice from the next code instance to customise the doughnut sequence utilizing the Radius, InnerRadius, PaletteBrushes, and different properties. 

<chart:DoughnutSeries ItemsSource="{Binding ProductionDetails}"                                  
                      XBindingPath="Nation" 
                      YBindingPath="Manufacturing"
                      ShowDataLabels="True"                      
                      PaletteBrushes="{Binding PaletteBrushes}"
                      Radius="{OnPlatform Android=0.6,Default=0.65,iOS=0.5}"
                      InnerRadius="0.5"/>

Customise the info labels 

Let’s customise the info labels utilizing the LabelTemplate help. Utilizing the LabelContext, we will tailor the label content material to show the share worth of the corresponding knowledge level. Moreover, use the SmartLabelAlignment property to rearrange the info labels intelligently, stopping them from overlapping.

Seek advice from the next code instance. 

<chart:SfCircularChart x:Identify="chart" Margin="{OnPlatform Default="0,0,0,0",iOS='-35,0,0,0'}" >
    <chart:SfCircularChart.Assets>
        <DataTemplate x:Key="labelTemplate">
            <HorizontalStackLayout Spacing="5">
                <Picture Supply="{Binding Merchandise.FlagImage}" VerticalOptions="Middle"  HeightRequest="{OnPlatform Android=20,Default=30,iOS=20}" WidthRequest="{OnPlatform Android=20,Default=30,iOS=20}" />
                <Label Textual content="{Binding Merchandise.Nation}" VerticalOptions="Middle"  FontFamily="centurygothic"  FontSize="{OnPlatform Android=15,Default=20,iOS=15}"/>
                <Label Textual content="{Binding Merchandise.Manufacturing,StringFormat=": {0}%"}" Margin="-4,0,0,0" VerticalOptions="Middle"  FontFamily="centurygothic"  FontSize="{OnPlatform Android=15,Default=20,iOS=15}"/>
            </HorizontalStackLayout>
        </DataTemplate>
    </chart:SfCircularChart.Assets>
    . . .
    <chart:DoughnutSeries ItemsSource="{Binding ProductionDetails}"                                  
                          XBindingPath="Nation" 
                          YBindingPath="Manufacturing"
                          ShowDataLabels="True"  
                          LabelContext="Proportion"
                          LabelTemplate="{StaticResource labelTemplate}"
                          PaletteBrushes="{Binding PaletteBrushes}"
                          Radius="{OnPlatform Android=0.6,Default=0.65,iOS=0.5}"
                          InnerRadius="0.5">
        <chart:DoughnutSeries.DataLabelSettings>
            <chart:CircularDataLabelSettings SmartLabelAlignment="Shift" LabelPosition="Exterior">
                <chart:CircularDataLabelSettings.ConnectorLineSettings>
                    <chart:ConnectorLineStyle ConnectorType="Line" StrokeWidth="3"></chart:ConnectorLineStyle>
                </chart:CircularDataLabelSettings.ConnectorLineSettings>
            </chart:CircularDataLabelSettings>
        </chart:DoughnutSeries.DataLabelSettings>
    </chart:DoughnutSeries>
</chart:SfCircularChart>

Including a middle view to the Doughnut Chart

Now, configure the CenterView property so as to add content material concerning the chosen knowledge phase’s oil manufacturing on the heart of the chart.

Seek advice from the next code instance.

<chart:DoughnutSeries.CenterView>
    <VerticalStackLayout Spacing="{OnPlatform Android=3.5,Default=7,iOS=3.5}">
        <Picture HorizontalOptions="Middle" 
                Opacity="0.8"
                HeightRequest="{OnPlatform Android=15,Default=50,iOS=15}"
                WidthRequest="{OnPlatform Android=15,Default=50,iOS=15}"
                Margin="{OnPlatform Default="5,0,0,0", Android='2.5,0,0,0'}"
                Supply="oildrum.png"/>
        <Label HorizontalOptions="Middle" FontFamily="centurygothic" FontAttributes="Daring" FontSize="{OnPlatform Android=10,Default=21,iOS=10}"  Textual content="{Binding CountryName,Supply={x:Reference worldOilProduction}}"/>
        <Label HorizontalOptions="Middle" FontFamily="centurygothic" FontAttributes="Daring" FontSize="{OnPlatform Android=10,Default=20,iOS=10}" Textual content="{Binding ProductionValue,Supply={x:Reference worldOilProduction},StringFormat="{0}M"}" />
    </VerticalStackLayout>
</chart:DoughnutSeries.CenterView>

Add interactive options

Utilizing the ExplodeOnTouch property, we will add interactive options to view the info for the exploded phase in our Chart. Exploding a phase helps pull consideration to a selected space of the Chart.

Right here, we’ll bind the ExplodeIndex property to the sequence heart view to indicate extra details about the info.

Seek advice from the next code instance.

<chart:DoughnutSeries ItemsSource="{Binding ProductionDetails}"                                  
                      XBindingPath="Nation" 
                      YBindingPath="Manufacturing"
                      . . .
                      ExplodeOnTouch="True"
                      ExplodeIndex="{Binding ExplodeIndex,Mode=TwoWay}"/>

After executing the above code examples, we are going to get the output that resembles the next picture. 

Visualizing the world’s biggest oil producers’ data using the Syncfusion .NET MAUI Doughnut Chart
Visualizing the world’s largest oil producers’ knowledge utilizing the Syncfusion .NET MAUI Doughnut Chart

Supercharge your cross-platform apps with Syncfusion’s sturdy .NET MAUI controls.

Strive It Free

GitHub reference

For extra particulars, check with visualizing the world’s largest oil producers in 2023 utilizing the .NET MAUI Doughnut Chart GitHub demo.

Conclusion

Thanks for studying! On this weblog, we’ve seen how you can use the Syncfusion .NET MAUI Doughnut Chart to visualise the world’s largest oil producers in 2023. We strongly encourage you to comply with the steps outlined on this weblog and share your ideas within the feedback beneath.

The prevailing prospects can obtain the brand new model of Important Studio on the License and Downloads web page. In case you are not a Syncfusion buyer, attempt our 30-day free trial to take a look at our unbelievable options. 

You too can contact us by our help boardshelp portal, or suggestions portal. We’re all the time completely satisfied to help you!

Associated blogs

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments