DEV Community

Cover image for Chart of the Week: Visualizing Top 25 Largest Countries Using .NET MAUI Column Chart
Lucy Muturi for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

Chart of the Week: Visualizing Top 25 Largest Countries Using .NET MAUI Column Chart

TL;DR: Visualize the top 25 largest countries of the world using the Syncfusion .NET MAUI Column Chart. This blog covers steps like gathering data, preparing data models, configuring the chart, customizing data labels and tooltips, applying gradient effects, and customizing the chart title and axes for better readability and visual appeal.

Welcome to our Chart of the Week blog series!

Today, we’ll visualize the top 25 largest countries by area using the Syncfusion .NET MAUI Column Chart.

The .NET MAUI Column Chart offers powerful customization options to enhance your data visualization experience. We’ll guide you through various techniques to make our chart visually appealing and informative. Specifically, we will cover:

  • Adding background images to the chart.
  • Customizing data labels and tooltips for more precise insights.
  • Applying gradient backgrounds to chart segments for a polished look.

Each of these customization will help you create a more dynamic and visually appealing chart.

Refer to the following image.Visualizing the top 25 largest counties in the world using Syncfusion .NET MAUI Column Chart

Let’s see the steps involved in creating this chart!

Step 1: Gather data

First, gather data on the top 25 world’s largest countries by area from worldometer site. Next, organize this information into an Excel spreadsheet, listing each country and its corresponding area, then save the file in CSV format.

Step 2: Preparing data for the chart

Create a Model class that includes properties for storing information about a country’s name and its total area.

public class Model
{
    public string CountryName { get; set; }
    public double TotalArea { get; set; }
    public Model(string countryName, double totalArea)
    {
        CountryName = countryName;
        TotalArea = totalArea;
    }
}
Enter fullscreen mode Exit fullscreen mode

In the ViewModel, read the CSV file contents using the StreamReader method and store the data in an ObservableCollection. Use a foreach loop to iterate through each item, then add each item to the AreaDetails property.

Refer to the following code example.

public ViewModel()
{
    AreaDetails = new List();
    ReadCSVFile();
}

private void ReadCSVFile()
{
    Assembly executingAssembly = typeof(App).GetTypeInfo().Assembly;
    Stream inputStream = executingAssembly.GetManifestResourceStream("SampleDemo.Resources.WorldLandDetails.csv");
    string line;
    ObservableCollection lines = new ObservableCollection();
    if (inputStream != null)
    {
        using StreamReader reader = new StreamReader(inputStream);
        while ((line = reader.ReadLine()) != null)
        {
            lines.Add(line);
        }
        lines.RemoveAt(0);
        foreach (var items in lines)
        {
            string[] data = items.Split(',');
            string countryName = data[0];
            double totalArea = Convert.ToDouble(data[1]);
            AreaDetails.Add(new Model(countryName, totalArea));
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure the .NET MAUI Column Chart and add background images

Now, configure the Syncfusion .NET MAUI Cartesian Charts control using this documentation. Then, create an instance of ColumnSeries, and bind the CountryName and TotalArea properties to the XBindingPath and YBindingPath properties, respectively. Additionally, set the ItemsSource property to the AreaDetails collection.

<chart:SfCartesianChart>
 <chart:ColumnSeries ItemsSource="{Binding AreaDetails}"
                     XBindingPath="CountryName" 
                     YBindingPath="TotalArea"
 </chart:ColumnSeries>
</chart:SfCartesianChart>
Enter fullscreen mode Exit fullscreen mode

The CartesianChart supports setting any kind of view as the chart background. We can achieve this in two ways:

Here, we’ll use the grid panel overlap option to set the background image to the whole screen. Refer to the following code example.

<Border StrokeShape="RoundRectangle 20" 
        StrokeThickness="4"
        Stroke="Gray"
        Margin="5">
 <Grid>
  <!-- Background image with opacity -->
  <Image Source="background.png"
         Aspect="AspectFill"
         Opacity="0.7"
         VerticalOptions="FillAndExpand"
         HorizontalOptions="FillAndExpand"/>
 </Grid>
</Border>
Enter fullscreen mode Exit fullscreen mode

Step 4: Adding and customizing data labels

Data labels help us display information for each data point within a chart. To enable data labels on a chart, set the ShowDataLabels property to True. We can also customize the appearance of these labels using the LabelTemplate property.

Then, we’ll create an image source as a data template and bind the CountryFlags property using the data label’s binding context of the name Item. Next, we’ll assign this custom data template to the LabelTemplate property. Using the LabelPlacement property, we can position the data label outside the segment, which is available in the CartesianDataLabelSettings class.

Refer to the following code example.

<chart:SfCartesianChart>
<chart:SfCartesianChart.Resources>
 <!--Custom data template-->
  <DataTemplate x:Key="dataTemplate">
   <Image Source="{Binding Item.CountryFlags}}" 
          HeightRequest="35" 
          WidthRequest="35"/>
  </DataTemplate>

  <chart:ColumnSeries ItemsSource="{Binding AreaDetails}"
                      XBindingPath="CountryName" 
                      YBindingPath="TotalArea"
                      ShowDataLabels="True"
                      LabelTemplate="{StaticResource dataTemplate}">
   <chart:ColumnSeries.DataLabelSettings>
    <chart:CartesianDataLabelSettings LabelPlacement="Outer"/>
   </chart:ColumnSeries.DataLabelSettings>
  </chart:ColumnSeries>

</chart:SfCartesianChart>
Enter fullscreen mode Exit fullscreen mode

Step 5: Adding and customizing tooltips

With the help of tooltips, we can include additional context or details when users hover or interact with chart elements. To enable tooltips, set the EnableTooltip property to True. We can also customize the appearance of tooltips using the TooltipTemplate property.

In this section, we’ll create a custom tooltip template and bind the country name and total area values using the tooltip’s binding context of the name Item. Finally, we’ll apply this custom template by setting it to the TooltipTemplate property.

<chart:SfCartesianChart>
 <chart:SfCartesianChart.Resources>
  <!--Custom tooltip template-->
  <DataTemplate x:Key="tooltipTemplate">
      <Grid RowDefinitions="*,*" ColumnDefinitions="*,Auto">
          <Label Text="Country:"
                 TextColor="White"
                 FontSize="12"
                 Grid.Row="0"
                 Grid.Column="0"
                 VerticalOptions="Center"
                 HorizontalOptions="End"/>

          <Label Text="{Binding Item.CountryName, StringFormat=' {0}'}"
                 TextColor="White"
                 FontSize="12"
                 Grid.Row="0"
                 Grid.Column="1"
                 VerticalOptions="Center"
                 HorizontalOptions="Start"/>

          <Label Text="Total Area:"
                 TextColor="White"
                 FontSize="12"
                 Grid.Row="1"
                 Grid.Column="0"
                 VerticalOptions="Center"
                 HorizontalOptions="End"/>

          <Label Text="{Binding Item.TotalArea, StringFormat=' {0} KM²'}"
                 TextColor="White"
                 FontSize="12"
                 Grid.Row="1"
                 Grid.Column="1"
                 VerticalOptions="Center"
                 HorizontalOptions="Start"/>
      </Grid>
  </DataTemplate>                   

</chart:SfCartesianChart.Resources>
   ….
 <chart:ColumnSeries EnableTooltip="True" TooltipTemplate="{StaticResource tooltipTemplate}"/>
</chart:SfCartesianChart>
Enter fullscreen mode Exit fullscreen mode

Step 6: Applying the gradient effect to the chart

Let’s enhance the visual appeal of the column series in the chart by applying a gradient effect. This can be achieved using the Fill property in conjunction with the LinearGradientBrush class. The StartPoint and EndPoint properties define the direction of the gradient. Here, the gradient runs vertically from top to bottom. The GradientStop elements specify the colors for different data points to replicate the gradient effect.

Refer to the following code example.

<chart:SfCartesianChart>
 <!--Column Series-->
  <chart:ColumnSeries ItemsSource="{Binding AreaDetails}"
                      XBindingPath="CountryName" 
                      YBindingPath="TotalArea">
   <chart:ColumnSeries.Fill>
     <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
      <GradientStop Color="#10e4b3" Offset="0" />
      <GradientStop Color="#0cd4e2" Offset="1" />
     </LinearGradientBrush>
  </chart:ColumnSeries.Fill>
</chart:SfCartesianChart>
Enter fullscreen mode Exit fullscreen mode

Step 7: Customizing the chart title

In this step, we’ll focus on customizing chart titles for better readability.

  • Apply a border and background color: Use the Border element to add a border around the chart title. This improves readability by visually separating the title from the rest of the chart.
  • Add title and description: Inside the border, use a Grid layout to arrange an icon, chart title, and description.

Refer to the following code example.

<Grid RowDefinitions="65,*">

 <!--Title and description of the chart-->
 <Border Grid.Row="0" 
         BackgroundColor="#ffffff" 
         HorizontalOptions="Start"
         StrokeShape="RoundRectangle 20"
         Margin="7,5,0,0"
         Padding="0,0,15,0">

  <Grid ColumnDefinitions="60,*" RowDefinitions="50,*">
   <Image Grid.RowSpan="1" Grid.Column="0" Source="titleicon.png"
          HeightRequest="45"
          WidthRequest="45"
          Margin="0,8,0,0" 
    <VerticalStackLayout Grid.Row="0" Grid.Column="1">
     <Label Text="Top 25 Largest Countries in the World by Area"
            TextColor="Black"
            HorizontalOptions="Start
            FontSize="18"
            FontAttributes="Bold"
            Margin="5,5,0,0"/>

     <Label Text="Total area includes both land and water bodies (such as lakes, reservoirs, and rivers). KM² stands for square kilometers."
            TextColor="Black"
            HorizontalOptions="Start"
            FontSize="12"
            Margin="5,5,0,0"/>
    </VerticalStackLayout>
  </Grid>
 </Border>  
</Grid>
Enter fullscreen mode Exit fullscreen mode

Step 8: Customizing the axes

To enhance the appearance and functionality of the primary and secondary axes, we can use the following properties:

Refer to the following code example.

<chart:SfCartesianChart>
  <chart:SfCartesianChart.XAxes>
      <chart:CategoryAxis ShowMajorGridLines="False" 
                          IsVisible="False"
                          PlotOffsetEnd="10"
                          PlotOffsetStart="10"
                          AutoScrollingMode="{OnPlatform Android=Start,iOS=Start}"
                          AutoScrollingDelta="{OnPlatform Default=0, Android=15 ,iOS=15}"/>
  </chart:SfCartesianChart.XAxes>

  <chart:SfCartesianChart.YAxes>
      <chart:NumericalAxis ShowMajorGridLines="False" 
                           Maximum="{OnPlatform Default=19000000,Android= 20000000, iOS=20000000 }">
          <chart:NumericalAxis.Title>
              <chart:ChartAxisTitle Text="Total Area(in KM²)"
                                    TextColor="White"/>
          </chart:NumericalAxis.Title>

          <chart:NumericalAxis.AxisLineStyle>
              <chart:ChartLineStyle Stroke="White"/>
          </chart:NumericalAxis.AxisLineStyle>

          <chart:NumericalAxis.MajorTickStyle>
              <chart:ChartAxisTickStyle Stroke="White"/>
          </chart:NumericalAxis.MajorTickStyle>

          <chart:NumericalAxis.LabelStyle>
              <chart:ChartAxisLabelStyle TextColor="White"/>
          </chart:NumericalAxis.LabelStyle>
      </chart:NumericalAxis>
  </chart:SfCartesianChart.YAxes>
          ….
</chart:SfCartesianChart>
Enter fullscreen mode Exit fullscreen mode

After executing these code examples, we will get the output that resembles the following image.

Visualizing the top 25 largest counties in the world using Syncfusion .NET MAUI Column Chart
Visualizing the top 25 largest counties in the world using Syncfusion .NET MAUI Column Chart

GitHub reference

For more details, refer to visualizing the top 25 largest countries in the world using the .NET MAUI Column Chart GitHub demo.

Conclusion

Thanks for reading! In this blog, we’ve explored how to visualize the top 25 largest countries in the world by area using the Syncfusion .NET MAUI Column Chart. Please follow the guidelines outlined in this blog and share your thoughts in the comments below.

The existing customers can download the latest version of Essential Studio from the License and Downloads page. If you are new, try our 30-day free trial to explore our incredible features.

You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!

Related blogs

Top comments (0)