Monday, February 10, 2025
HomeC#Unlock Perception into G7 International locations' Debt with the Flutter Vary Column...

Unlock Perception into G7 International locations’ Debt with the Flutter Vary Column Chart


TL;DR: Let’s visualize the G7 international locations’ debt projections from 2024 to 2029 utilizing the Syncfusion Flutter Vary Column Chart. We’ll customise the chart with customized knowledge labels, tooltips, and a tailor-made column sequence for higher insights. The chart will show debt adjustments with color-coded columns, annotations, and flags for readability. This method helps evaluate debt projections successfully throughout international locations.

Welcome to our Chart of the Week blog sequence!

On this weblog, we’ll visualize the debt projections for G7 international locations from 2024 to 2029 utilizing the Syncfusion Flutter Vary Column Chart. This chart will present adjustments in debt ranges throughout international locations, with customized labels and annotations for added readability. With these enhancements, we will simply evaluate debt projections for every nation.

Vary column chart

A Vary Column Chart shows knowledge as vertical bars, exhibiting each minimal and most values for every class. It’s excellent for illustrating adjustments, reminiscent of development or decline, inside particular teams. This chart is particularly helpful for evaluating ranges, like debt adjustments over time throughout completely different international locations.

Customized knowledge label

Customized knowledge labels permit us to show essential data instantly on the chart, making it simpler for viewers to know the information. On this visualization, we’ll customise the information labels to indicate nation names and icons. Syncfusion Flutter Charts make this easy utilizing the builder property within the dataLabelSettings, permitting for a extremely tailor-made show.

Customized tooltip

The customized tooltipBehavior in Flutter Charts enhances interactivity by displaying detailed data when a consumer faucets or hovers on a chart level. On this instance, we’ll customise the tooltip to show debt data for particular years.

The builder property helps a personalised tooltip structure. We’ll use it to indicate the debt percentages for 2024 and 2029 and the distinction between them. This method makes the tooltip extra informative and visually partaking, bettering the general consumer expertise when interacting with the chart.

Customized vary column sequence

A customized vary column sequence permits for superior customization of the vary column chart’s look. Utilizing a customized renderer, we will modify how every column must be drawn and apply distinctive kinds like gradients, customized borders, and results. This customization enhances the chart’s visible enchantment and interactivity.

The onCreateRenderer property is essential to implementing a customized renderer, offering full management over the rendering course of. With this characteristic, you’ll be able to tailor the chart to satisfy particular design necessities and create extra partaking visualizations.

Let’s visualize the federal government debt projections for G7 international locations utilizing the Syncfusion Flutter Vary Column Chart!

Consult with the next picture.

Visualizing government debt project for G7 countries using Flutter Range Column Chart
Visualizing authorities debt mission for G7 international locations utilizing Flutter Vary Column Chart

Step 1: Gathering the information

Let’s collect knowledge on authorities debt projections for G7 international locations from the Worldwide Financial Fund, together with every nation’s gross debt in 2024 and 2029 and the distinction in share factors between these years.

Step 2: Outline and populate knowledge on the chart

Now, outline a G7DebtData mannequin class that accommodates particulars for the nation title, yr 2024 debt, yr 2029 debt, the proportion change between the present yr debt and the projected yr debt, and a section coloration to replace the colour for every section.

Consult with the next code instance.

class G7DebtData {
  G7DebtData(this.nation, this.year2024Debt, this.year2029Debt, this.percentageChange, this.segmentColor);
  ultimate String nation;
  ultimate double year2024Debt;
  ultimate double year2029Debt;
  ultimate double percentageChange;
  ultimate Coloration segmentColor;
}

Then, create a listing to carry the federal government debt projection knowledge from the monetary yr 2024 to 2029, which can be used as the information supply for the vary column chart.

Consult with the next code instance.

late Checklist<G7DebtData> _g7DebtData;

@override
void initState() {
  _g7DebtData = [
    G7DebtData( 'USA', 123.3, 133.9, 10.6, const Color.fromARGB(255, 24, 109, 255)),
    G7DebtData('UK', 104.3, 110.1, 5.8, const Color.fromARGB(255, 187, 0, 255)),
    G7DebtData('Italy', 139.2, 144.9, 5.7, const Color.fromARGB(255, 40, 255, 133)),
    G7DebtData('France', 111.6, 115.2, 3.6, const Color.fromARGB(255, 39, 194, 255)),
    G7DebtData('Japan', 254.6, 251.7, -2.9, const Color.fromARGB(255, 255, 38, 89)),
    G7DebtData('Germany', 63.7, 57.7, -6.0, const Color.fromARGB(255, 153, 255, 1)),
    G7DebtData('Canada', 104.3, 95.4, -9.3, const Color.fromARGB(255, 255, 33, 33)),
  ];
  tremendous.initState();
}

Step 3: Configuring the Flutter Vary Column Chart

To visualise the federal government debt projections, we’ll use theSyncfusion Flutter RangeColumnSeries. The X-axis is ready to CategoryAxis, which represents the nation names, whereas the Y-axis is ready to NumericAxis, displaying the change in authorities debt as numeric values.

The RangeColumnSeries is configured to indicate the vary of values by mapping the high and low values utilizing lowValueMapper and highValueMapper, respectively. The colour of every column is dynamically assigned utilizing pointColorMapper, which makes use of the segmentColor from the information, guaranteeing every nation is visually distinct within the chart.

This method permits the consumer to simply evaluate debt adjustments for every nation, with the additional benefit of color-coding for readability.

Consult with the next code instance.

@override
Widget construct(BuildContext context) {
  return Scaffold(
    physique: SfCartesianChart(
      primaryXAxis: CategoryAxis(),
      primaryYAxis: NumericAxis(),
      sequence: [
        RangeColumnSeries< G7DebtData, String>(
          dataSource: _ g7DebtData,
          xValueMapper: (G7DebtData data, int index) =>  data.country,
          lowValueMapper: (G7DebtData data, int index) => data.change > 0 ? 0 :       
            data.percentageChange,
          highValueMapper: (G7DebtData data, int index) => data.change > 0 ? 
            data.percentageChange : 0,
          pointColorMapper: (G7DebtData data, int index) => data.segmentColor,
        ),

Refer to the following image.

Rendering Flutter Range Column Chart
Rendering Flutter Range Column Chart

Step 4: Customizing axis appearance

Here, we’ll disable the X-axis by setting the isVisible property to false, keeping the chart clean without displaying the axis.

The Y-axis is customized with the title “Percentage Point Change 2024 to 2029” and hides the axis line and tick lines. The Grid lines are faint with a width of 0.5. The range is set from -14 to 14 and positioned on the opposite side for better readability.

Refer to the following code example.

plotAreaBorderWidth: 0,
primaryXAxis: CategoryAxis(
  isVisible: false,
),
primaryYAxis: NumericAxis(
  title: AxisTitle(text: 'Percentage Point Change 2024 to 2029'),
  axisLine: AxisLine(width: 0),
  majorTickLines: MajorTickLines(width: 0),
  majorGridLines: MajorGridLines(width: 0.5, color: Colors.grey),
  minimum: -14,
  maximum: 14,
  opposedPosition: true,
),

Refer to the following image.

Customizing axis appearance in Flutter Range Column Chart
Customizing axis appearance in Flutter Range Column Chart

Step 5: Adding chart title

The ChartTitle widget is used to customize the title in this chart. The text property is set to “G7 Government Debt Projections (2024-2029).” The title text is styled with textStyle. The title is set to bold for a clear, prominent appearance at the top of the chart.

Refer to the following code example.

title:ChartTitle(
  text: 'G7 Government Debt Projections (2024-2029)',
  textStyle: TextStyle(fontWeight: FontWeight.bold),
),

Refer to the following image.

Adding a title to the Flutter Range Column Chart
Adding a title to the Flutter Range Column Chart

Step 6: Create and configure a custom range column series renderer

The onCreateRenderer callback is used to create a custom series renderer for the range column chart. By returning the _CustomRangeColumnSeriesRenderer, you can extend the default renderer to apply unique visualizations to each segment.

The custom renderer handles tasks such as creating segments from data points and customizing how the chart is drawn. This allows for greater flexibility and personalization when displaying the chart’s data.

Refer to the following code example.

series: [
  RangeColumnSeries< G7DebtData, String>(
    ....
    onCreateRenderer: (series) {
      return _CustomRangeColumnSeriesRenderer();
    },
  ),
]

The _CustomRangeColumnSeriesRenderer class extends RangeColumnSeriesRenderer to create a customized visualization utilizing the GovernmentDebtProjectionData mannequin. It overrides the createSegment technique to return a customized section, _RangeColumnCustomPainter, which handles the precise drawing necessities. The onPaint technique customizes every section’s measurement and place utilizing segmentRect and applies a gradient for visible depth.

The important thing customizations embody:

  • Circles: Drawn on the high and backside of every section, with coloration adjustments indicating optimistic or adverse debt adjustments.
  • Textual content Labels: Displayed on the high, backside, and heart of every section, representing projected debt, present debt, and share change. These labels are dynamically positioned and styled for readability.

This mixture of visible enhancements ensures the chart is partaking, informative, and simple to interpret.

Consult with the next code instance.

class _CustomRangeColumnSeriesRenderer extends RangeColumnSeriesRenderer<G7DebtData, String> {
    _CustomRangeColumnSeriesRenderer();

    @override
    RangeColumnSegment< G7DebtData, String> createSegment() {
      return _RangeColumnCustomPainter();
    }
}

class _RangeColumnCustomPainter extends RangeColumnSegment< G7DebtData, String> {
  _RangeColumnCustomPainter();

  void paintText(Canvas canvas, String textual content, Offset place, double fontSize,
      {bool isCenter = false, Coloration baseColor = Colours.black}) {
    ultimate TextSpan span = TextSpan(
      type: TextStyle(
        coloration:
            isCenter ? Coloration.lerp(baseColor, Colours.black, 0.50)! : baseColor,
        fontSize: fontSize,
        fontWeight: FontWeight.daring,
      ),
      textual content: textual content,
    );

    ultimate TextPainter tp = TextPainter(
      textual content: span,
      textAlign: TextAlign.heart,
      textDirection: TextDirection.ltr,
    );
    tp.structure();
    tp.paint(canvas,
        Offset(place.dx - tp.width / 2, place.dy - tp.peak / 2));
  }

  void drawCustomCircle(Canvas canvas, Offset heart, double radius,
      Paint fillPaint, Paint strokePaint) {
    canvas.drawCircle(heart, radius, fillPaint);
    canvas.drawCircle(heart, radius - 1, strokePaint);
  }

  @override
  void onPaint(Canvas canvas) {
    if (segmentRect == null) return;
    ultimate double heart = segmentRect!.heart.dx;
    ultimate double high = segmentRect!.high;
    ultimate double backside = segmentRect!.backside;
    ultimate section = sequence.dataSource![currentSegmentIndex];
    ultimate double centerText = section.change;
    ultimate bool isPositiveChange = centerText > 0;
    ultimate double topText =
        isPositiveChange ? section.projectedYearDebt : section.currentYearDebt;
    ultimate double bottomText =
        isPositiveChange ? section.currentYearDebt : section.projectedYearDebt;

    ultimate Paint customPaint = Paint()
      ..coloration = Coloration.lerp(fillPaint.coloration, Colours.white, 0.40)!
      ..type = PaintingStyle.fill;
    ultimate Gradient gradient = LinearGradient(
      colours: [fillPaint.color, customPaint.color],
      start: isPositiveChange ? Alignment.bottomCenter : Alignment.topCenter,
      finish: isPositiveChange ? Alignment.topCenter : Alignment.bottomCenter,
    );

    ultimate Paint gradientPaint = Paint()
      ..shader = gradient.createShader(segmentRect!.outerRect);
    ultimate Paint strokePaint = Paint()
      ..coloration = fillPaint.coloration
      ..type = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    canvas.drawRRect(segmentRect!, gradientPaint);
    drawCustomCircle(canvas, Offset(heart, high), segmentRect!.width / 2,
        isPositiveChange ? customPaint : fillPaint, strokePaint);
    drawCustomCircle(canvas, Offset(heart, backside), segmentRect!.width / 2,
        isPositiveChange ? fillPaint : customPaint, strokePaint);

    paintText(canvas, '${topText.spherical()}%', Offset(heart, high), 20);
    paintText(canvas, '${bottomText.spherical()}%', Offset(heart, backside), 20);
    if (centerText.abs() > 5) {
      paintText(
        canvas,
        '${centerText >= 0 ? '+' : ''}${centerText.spherical()}pp',
        segmentRect!.heart,
        25,
        isCenter: true,
        baseColor: fillPaint.coloration,
      );
    }
  }
}

Consult with the next picture.

Configuring a custom range column series renderer for Flutter Range Column Chart
Configuring a customized vary column sequence renderer for Flutter Vary Column Chart

Step 7: Including customized knowledge labels to the chart

To make the chart extra partaking, customized knowledge labels are added to show every nation’s flag on the high of their respective columns utilizing the builder property within the dataLabelSettings.

On this setup, the builder checks the pointIndex and dynamically returns both the nation’s flag or its title. If the flag is displayed, the picture is loaded from a neighborhood listing, with the file title matching the nation area from the GovernmentDebtProjectionData object. The flag is styled inside a round container with a border for visible distinction.

Consult with the next code instance.

RangeColumnSeries< G7DebtData, String>(
dataLabelSettings: DataLabelSettings(
  isVisible: true,
  builder: (dynamic knowledge, dynamic level, dynamic sequence,
    int pointIndex, int seriesIndex) {
    ultimate bool isDifferentIndex = pointIndex != index;
    index = pointIndex;
    ultimate Widget content material = isDifferentIndex ? Container(width: 30, peak: 30,
        ornament: BoxDecoration(
          border: Border.all(coloration: Colours.black, width: 2),
          borderRadius: BorderRadius.round(50),
        ),
        youngster: Picture.asset(
          'Picture/${knowledge.nation}.png',
           width: 30,
           peak: 30,
           match: BoxFit.include,
        ),
      )
      : Textual content(
        '${knowledge.nation}',
         type: TextStyle(fontWeight: FontWeight.daring),
      );
      return Padding(
        padding: EdgeInsets.solely(backside: isDifferentIndex ? 50 : 0, high: isDifferentIndex ? 0 : 50),
        youngster: content material,
       );
    },
 ),

Moreover, the required flag photos must be added to the belongings in your pubspec.yaml file to make sure correct loading and show of every nation’s flag within the chart. This method provides the chart a visually interesting and informative contact.

Consult with the next code instance.

flutter:
  belongings:
    - ImageCanada.png
    - ImageFrance.png
    - ImageGermany.png
    - ImageItaly.png
    - ImageJapan.png
    - ImageUK.png
    - ImageUSA.png

Consult with the next picture.

Adding data labels to the Flutter Range Column Chart
Including knowledge labels to the Flutter Vary Column Chart

Step 8: Including annotations to the chart

The CartesianChartAnnotation class is used so as to add a customized annotation, explaining the projected change in authorities debt from 2024 to 2029. The textual content is centered in a container with rounded corners, a border, and a background coloration for readability.

The annotation is positioned at particular chart coordinates to assist customers perceive the information, with bars above zero indicating a rise and people beneath exhibiting a lower in debt.

Consult with the next code instance.

annotations: <CartesianChartAnnotation>[
  CartesianChartAnnotation(
    widget: Container(
      height: 100,
      width: 320,
      decoration: BoxDecoration(
        color: ThemeData().canvasColor,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(width: 1, color: Colors.black)),
        alignment: Alignment.center,
        child: Text(
                'Each bar shows the projected change in ngovernment debt (% of GDP) from 2024 to         
                 2029.nBars above zero indicate an increase in debt, nwhile those below zero show           
                 a decrease.',
          style: TextStyle(fontSize: 14),
          textAlign: TextAlign.center,
         ),
       ),
      x: 570,
      y: 120,
      coordinateUnit: CoordinateUnit.logicalPixel,
    ),
],

Consult with the next picture.

Adding annotations to the Flutter Range Column Chart
Including annotations to the Flutter Vary Column Chart

Step 9: Including a customized tooltip to the chart

Customized tooltips are added utilizing the tooltipBehavior property to indicate detailed knowledge when interacting with a column. The builder shows the nation title and emblem on the high, together with the debt for 2024 and 2029 and the proportion distinction, all in daring textual content on a background coloration primarily based on the section.

This makes the chart extra interactive by offering further data when a consumer faucets or hovers over a section.

Consult with the next code instance.

tooltipBehavior: TooltipBehavior(
  allow: true,
  builder: (dynamic knowledge, dynamic level, dynamic sequence, int pointIndex, int seriesIndex) {
    ultimate G7DebtData debtData = knowledge;
    ultimate Coloration darkSegmentColor = Coloration.lerp(debtData.segmentColor, Colours.black, 0.70)!;
    ultimate Coloration lightSegmentColor = Coloration.lerp(debtData.segmentColor, Colours.white, 0.60)!;
    return Container(
      width: 155,
      padding: const EdgeInsets.all(8),
      ornament: BoxDecoration(
        coloration: lightSegmentColor,
        borderRadius: BorderRadius.round(5),
        border: Border.all(coloration: darkSegmentColor),
      ),
      youngster: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.begin,
        youngsters: [
          Center(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: 25,
                  height: 25,
                  decoration: BoxDecoration(
                    border:
                        Border.all(color: darkSegmentColor, width: 2),
                    borderRadius: BorderRadius.circular(50),
                  ),
                  child: Image.asset(
                    'Image/${debtData.country}.png',
                    fit: BoxFit.contain,
                  ),
                ),
                const SizedBox(width: 5),
                Text(
                  debtData.country,
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: darkSegmentColor),
                ),
              ],
            ),
          ),
          Divider(
              coloration: darkSegmentColor,
              thickness: 1,
              peak: 10,
              indent: 5,
              endIndent: 5),
          ...[
            'Debt in 2024: ${debtData.year2024Debt.round()}%',
            'Debt in 2029: ${debtData.year2029Debt.round()}%',
            'Difference: ${(debtData.percentageChange).round()}pp',
          ].map(
            (textual content) => Textual content(
              textual content,
              type: TextStyle(
                fontWeight: FontWeight.daring,
                coloration: darkSegmentColor,
              ),
            ),
          ),

Consult with the next picture.

Adding tooltip to the Flutter Range Column Chart
Including tooltips to the Flutter Vary Column Chart

GitHub reference

For extra particulars, seek advice from the Visualizing the federal government debt projections for G7 international locations utilizing the Flutter Vary Column Chart GitHub demo.

Unlock the ability of Syncfusion’s extremely customizable Flutter widgets.

Strive It Free

Conclusion

Thanks for studying! On this weblog, we’ve seen easy methods to visualize the federal government debt projections for G7 international locations utilizing the Syncfusion Vary Column Chart. We hope you discover the outlined steps useful in reaching comparable outcomes.

If you happen to’re an present buyer, you’ll be able to obtain the most recent model of Important Studio® from the License and Downloads web page. For these new to Syncfusion, attempt our 30-day free trial to discover all our options.

For queries, you’ll be able to contact us via our assist discussion board, assist portal, or suggestions portal. As at all times, we’re glad to help you!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments