Monday, April 21, 2025
HomeC#Visualizing World Coal Consumption Tendencies with Our Flutter Stacked Space Chart

Visualizing World Coal Consumption Tendencies with Our Flutter Stacked Space Chart


TL;DR: Let’s visualize world coal consumption tendencies utilizing the Flutter Stacked Space Chart. We’ll discover how totally different areas contribute to whole coal use over time. This information covers information preparation, chart customization, and interactive enhancements like picture overlays. Be taught to construct an insightful visualization utilizing our Flutter Charts!

Welcome to the Chart of the Week weblog collection!

Charts are an effective way to visualise the information, making it simpler to know by presenting it clearly and visually. Among the many various kinds of charts, stacked space charts are particularly helpful for displaying how totally different components add as much as whole time beyond regulation. They’re nice for displaying patterns, evaluating teams, and monitoring mixed values, serving to you see how particular person components contribute to the entire. This makes stacked space charts a sensible choice for understanding information from a number of teams, like areas or industries, the place each particular person and total tendencies matter.

This weblog is about displaying world coal consumption tendencies utilizing the Syncfusion Flutter Stacked Space Chart. We’ll see create an interactive chart that exhibits coal use in numerous areas over time. From getting ready the information to customizing the chart, this information provides easy steps to construct a transparent and efficient visualization. You’ll find out how areas like Asia, Europe, and America have contributed to world coal consumption, making exploring and understanding the information straightforward.

Stacked Space Chart

The StackedAreaSeries is part of the SfCartesianChart widget, designed to visualise how a number of information collection mix to type a cumulative whole time beyond regulation or a selected class. Every collection is represented as a crammed space, stacked one on prime of the opposite. 

The Stacked Space Chart permits us to plot a number of information collection on prime of one another, successfully displaying how particular person elements contribute to a cumulative whole. Every space’s peak represents its worth relative to your entire chart, making it straightforward to match totally different collection contributions at any time. The collection additionally helps customizing its components like colours, gradients, and borders, permitting you to customise the visible look based mostly in your wants. The interactive components, akin to tooltips and trackballs, improve the person’s potential to discover the information dynamically.

Key causes to make use of a Stacked Space Chart

  • Visualizing tendencies over time: Helps monitor how totally different classes contribute to the general pattern over a interval.
  • Efficient for part-to-whole relationships: Illustrates how particular person elements stack as much as type a cumulative worth.
  • Evaluating proportions: Reveals the relative contribution of every class to a complete whereas sustaining the visibility of the entire dataset.
  • Higher for giant information units: When a number of classes must be analyzed collectively relatively than individually.
  • Straightforward identification of progress patterns: Highlights growing or lowering tendencies throughout a number of classes.

Use instances of Stacked Space Charts

  • Monetary evaluation: Monitoring income, bills, and revenue contributions over time.
  • Web site analytics: Monitoring site visitors sources (natural, direct, paid, referral) over time.
  • Market share evaluation: Evaluating totally different firm shares inside the trade.
  • Vitality consumption: Displaying electrical energy consumption from totally different sources (photo voltaic, wind, fossil fuels).
  • Demographic evaluation: Visualizing inhabitants distribution by age teams throughout years.
  • Gross sales efficiency: Displaying product category-wise contribution to whole gross sales.

Let’s use the Flutter Stacked Space Chart to visualise the information on coal consumption worldwide! We’ll add a picture with overlay colours and annotations, as proven within the following picture.

Visualizing the coal consumption data in various regions using Flutter Stacked Area Chart

Enhancing StackedAreaSeries with picture overlays

The StackedAreaSeries successfully visualizes coal consumption tendencies over time, illustrating how totally different areas contribute to whole utilization. Layering the information highlights every area’s share whereas emphasizing total progress.  To reinforce visible enchantment, photographs are overlaid on every collection utilizing the onCreateRenderer property within the SfCartesianChart widget, guaranteeing a transparent and interesting chart by extending the StackedAreaSeriesRenderer.

Pictures are utilized as texture fills utilizing picture shaders within the onPaint methodology of the StackedAreaSegment. Moreover, an overlay colour blends the photographs easily with the background, making a visually distinct illustration of world coal consumption.

  • onCreateRenderer: Defines a renderer for the collection.
  • StackedAreaSeriesRenderer: Creates the renderer for StackedAreaSeries.
  • StackedAreaSegment: Handles the portray of every phase, permitting picture shaders and textures.

Moreover, annotations assist us so as to add further particulars or visuals to charts, making them extra informative and visually interesting. In SfCartesianChart, you should utilize the annotations property to position textual content, photographs, or shapes at particular positions on the chart. That is helpful for highlighting key information factors, including labels, or offering further context to the chart’s info.

Visualizing coal consumption information utilizing Flutter Stacked Space Chart

Comply with these steps to visualise the worldwide coal consumption tendencies utilizing the Flutter Stacked Space Chart!

Step 1: Gathering the information

Let’s gather information on world coal consumption (measured in Exajoules) from the Vitality Institute. This dataset consists of coal consumption tendencies throughout key areas, akin to Europe, North America, Asia-Pacific, and the remainder of the world, from 1965 to 2023.

Step 2: Outline and populate information to the chart

Now, outline the information representing coal consumption tendencies throughout totally different areas over time. This information will likely be used to plot the chart and visualize tendencies successfully.

Confer with the next code instance.

class CoalConsumptionData {
  ultimate String  yr;
  ultimate double  europe;
  ultimate double  restOfWorld;
  ultimate double  northAmerica;
  ultimate double  asiaPacific;

  CoalConsumptionData(
    this.yr, 
    this.europe, 
    this.restOfWorld, 
    this.northAmerica, 
    this.asiaPacific
  );
}

To characterize world coal consumption tendencies in Exajoules from 1965 to 2023, we’ll create an inventory named coalConsumptionData. This checklist will likely be used as the information supply for the Stacked Space Chart, offering a transparent visualization of the tendencies over time.

Confer with the next code instance.

late Listing<CoalConsumptionData> coalConsumptionData;

@override
void initState() {
  coalConsumptionData = [
    CoalConsumptionData('1965', 10, 14, 12, 22),
    CoalConsumptionData('1966', 11, 14, 13, 21),
    CoalConsumptionData('1967', 10, 15, 13, 20),
    CoalConsumptionData('1968', 10, 14, 13, 21),
    CoalConsumptionData('1969', 12, 15, 13, 21),
    CoalConsumptionData('1970', 13, 15, 13, 21),
    CoalConsumptionData('1971', 14, 15, 12, 20),
    // More data...
  ];
  tremendous.initState();
}

Step 3: Configuring the Flutter Stacked Space Chart

The SfCartesianChart is configured with a CategoryAxis because the primaryXAxis and a NumericAxis because the primaryYAxis to show coal consumption information over time. The X-axis represents years, whereas the Y-axis measures coal consumption in exajoules.

A number of StackedAreaSeries are used to visualise information for various areas, together with Asia-Pacific, the remainder of the world, North America, and Europe. This setup clearly represents coal consumption tendencies throughout totally different areas over time.

Confer with the next code instance.

SfCartesianChart(
  primaryXAxis: _createCategoryAxis(),
  primaryYAxis: _createNumericAxis(),
  collection: _buildStackedAreaSeries(),
);

Listing<StackedAreaSeries<CoalConsumptionData, String>> _buildStackedAreaSeries() {
  ultimate Listing<double Perform(CoalConsumptionData, dynamic)> regionDataMappers = [
    (CoalConsumptionData data, int index) => data.asiaPacific,
    (CoalConsumptionData data, int index) => data.restOfWorld,
    (CoalConsumptionData data, int index) => data.northAmerica,
    (CoalConsumptionData data, int index) => data.europe,
  ];

  return Listing.generate(4, (index) {
    return StackedAreaSeries<CoalConsumptionData, String>(
      dataSource: coalConsumptionData,
      xValueMapper: (CoalConsumptionData information, int index) => information.yr,
      yValueMapper: regionDataMappers[index],
      .....
    );
  });
}

Step 4: Configure axes and disable gridline look

The CategoryAxis (X-axis) represents years with an interval of three, guaranteeing labels seem each third yr for higher readability. It’s titled Years, and labels are aligned with axis ticks utilizing the labelPlacement property set to onTicks. Gridlines are disabled utilizing the majorGridLines by setting the width to 0, decreasing visible muddle.

The Y-axis labelPlacement property represents coal consumption in Exajoules with an interval of 20, offering evenly spaced tick marks. It’s titled Exajoules for readability. Just like the X-axis, main gridlines on the Y-axis are additionally disabled by setting the majorGridLines property as 0, making a clear and uncluttered chart structure.

The axisLabelFormatter operate is used to customise the chart axis labels dynamically. It shows the years which might be divisible by 10 (e.g., 1970, 1980) and shortens others to their final two digits (e.g., ’75’ for 1975), apart from the primary (1965) and final (2022) years.

Confer with the next code instance.

SfCartesianChart(
  primaryXAxis: _createCategoryAxis(),
  primaryYAxis: _createNumericAxis(),
  .....
);

CategoryAxis _createCategoryAxis() {
  return CategoryAxis(
    interval: 3,
    title: const AxisTitle(
      textual content: 'Years',
      textStyle: TextStyle(fontSize: 18, fontWeight: FontWeight.daring),
    ),
    labelPlacement: LabelPlacement.onTicks,
    majorGridLines: const MajorGridLines(width: 0),
    axisLabelFormatter: (AxisLabelRenderDetails particulars) ,
  );
}

NumericAxis _createNumericAxis() {
  return NumericAxis(
    interval: 20,
    majorGridLines: const MajorGridLines(width: 0),
    title: const AxisTitle(
      textual content: 'Exajoules',
      textStyle: TextStyle(fontSize: 18, fontWeight: FontWeight.daring),
    ),
  );
}

Step 5: Create and configure the Stacked Space collection renderer

The onCreateRenderer property within the SfCartesianChart widget permits us to outline a singular renderer for a collection. Because of this as a substitute of utilizing the default rendering conduct, we will modify how the StackedAreaSeries needs to be drawn by implementing a specialised renderer.

How does it work?

  1. We outline an lengthen renderer class (StackedAreaRendererExtension) that extends the default StackedAreaSeriesRenderer.
  2. The renderer creates an prolonged phase (StackedAreaSegmentExtension), which modifies how the collection is painted.
  3. The onCreateRenderer property is used within the StackedAreaSeries to switch the default renderer with our modified renderer.

Confer with the next code instance.

SfCartesianChart(
  .....
  collection: StackedAreaSeries<CoalConsumptionData, String>(
    .....
    onCreateRenderer: (ChartSeries<dynamic, dynamic> collection) => 
        StackedAreaRendererExtension(seriesStackedAreaSeries<CoalConsumptionData, String>),
  ),
);

Outline StackedAreaRendererExtension

The StackedAreaRendererExtension class extends StackedAreaSeriesRenderer. It retains monitor of the seriesIndex to know which collection it belongs to and makes certain a number of collection stack appropriately.

Now, the StackedAreaRendererExtension class overrides the createSegment() methodology to return a StackedAreaSegmentExtension. Then, the StackedAreaSegmentExtension handles the precise drawing, together with including textures and overlay colours and guaranteeing the segments are stacked in the precise order for a transparent and visually interesting look. The bottomBoundary property shops the underside boundary of the earlier phase.

Confer with the next code instance.

class StackedAreaRendererExtension<T, D> extends StackedAreaSeriesRenderer<T, D> {
  static ultimate Map<int, Listing<Offset>> bottomBoundary = {};

  StackedAreaRendererExtension(StackedAreaSeries<T, D> collection) : tremendous();

  @override
  StackedAreaSegment<T, D> createSegment() {
    return StackedAreaSegmentExtension<T, D>();
  }
}

Enhancing the Stacked Space phase

In our demo, the StackedAreaSegmentExtension class extends StackedAreaSegment. The StackedAreaSegmentExtension class is used to customise how every phase in a stacked space chart needs to be drawn by including background photographs and overlay colours. It assigns a singular picture and colour to every phase based mostly on the seriesIndex. To optimize the efficiency, the _loadImageForSeries() methodology is used to load photographs from property and retailer them within the _loadedImages property, stopping redundant loading. This ensures every phase has a definite visible type with out affecting efficiency.

The onPaint methodology handles the drawing course of by first producing the phase form with the _generateSegmentPath() methodology, after which making use of a picture background utilizing the ImageShader. A semi-transparent overlay colour is added for higher visibility, and a black border is drawn for clear separation.

The _buildBottomBoundaryPoints() methodology saves the underside boundary factors, guaranteeing the proper stacking of segments. This strategy enhances the chart’s readability and visible enchantment, making information illustration extra participating.

Confer with the next code instance.

class StackedAreaSegmentExtension<T, D> extends StackedAreaSegment<T, D> {
  ui.Picture? backgroundImage;
  static ultimate Map<int, ui.Picture> _loadedImages = {};
  ….
  Future<void> _loadImageForSeries() async {
    if (_loadedImages.containsKey(collection.index)) {
      backgroundImage = _loadedImages[series.index];
    } else {
      attempt {
        ultimate ByteData information = await rootBundle.load(photographs[series.index]);
        ultimate codec = await ui.instantiateImageCodec(information.buffer.asUint8List());
        ultimate body = await codec.getNextFrame();
        backgroundImage = body.picture;
        _loadedImages[series.index] = backgroundImage!;
      } catch (e) {
        debugPrint("Picture loading error: $e");
      }
    }
  }

  @override
  void onPaint(Canvas canvas) {
    if (factors.isEmpty) return;

    // Make sure the picture is loaded earlier than portray
    if (backgroundImage == null) {
      _loadImageForSeries();
      return;
    }

    Path segmentPath = _generateSegmentPath(canvas);
    _buildBottomBoundaryPoints();

    // Paint for the picture background
    Paint fillPaint = Paint()
      ..colour = Colours.black.withValues(alpha: 0.4)
      ..blendMode = BlendMode.darken
      ..shader = ImageShader(
        backgroundImage!,
        TileMode.repeated,
        TileMode.repeated,
        Matrix4.identification().storage,
      );

    canvas.drawPath(segmentPath, fillPaint);
  }

  Path _generateSegmentPath(Canvas canvas) {
    Path path = Path()..moveTo(factors.first.dx, factors.first.dy);
    for (int i = 1; i < factors.size; i++) {
      path.lineTo(factors[i].dx, factors[i].dy);
    }

    Listing<Offset> bottomPoints = StackedAreaRendererExtension.bottomBoundary[series.index - 1] ?? [];
    if (collection.index == 0 || bottomPoints.isEmpty) {
      double chartBottomY = canvas.getLocalClipBounds().backside;
      for (int i = factors.size - 1; i >= 0; i--) {
        path.lineTo(factors[i].dx, chartBottomY);
      }
    } else {
      for (int i = factors.size - 1; i >= 0; i--) {
        path.lineTo(bottomPoints[i].dx, bottomPoints[i].dy);
      }
    }
    return path..shut();
  }

  void _buildBottomBoundaryPoints() {
    StackedAreaRendererExtension.bottomBoundary[series.index] = Listing.from(factors);
  }
}

Moreover, the required coal photographs needs to be added to the property in your pubspec.yaml file to make sure correct loading and show of every picture within the chart. This strategy makes the chart visually interesting.

Confer with the next instance code.

flutter:
  property:
    - property/coal1.jpg
    - property/coal2.jpg
    - property/coal3.jpg

Step 6: Including annotations to the chart

Annotations permit further info or visible components to be positioned on the chart utilizing the annotations property, which accepts an inventory of CartesianChartAnnotation objects. The CartesianChartAnnotation methodology takes a widget, an x worth, and a y worth to place the annotation at particular coordinates by setting coordinateUnit to level.

Moreover, the SfCircularChart widget with a DoughnutSeries is used as an annotation to offer a visible illustration of information inside the Cartesian Chart. These annotations are strategically positioned utilizing x and y values, guaranteeing a transparent and structured option to visualize coal consumption information.

Confer with the next code instance.

SfCartesianChart(
  .....
  annotations: _createAnnotations(),
);

// Helper operate to create CartesianChartAnnotation
CartesianChartAnnotation _createAnnotation(Widget widget, String x, double y) {
  return CartesianChartAnnotation(
    widget: widget,
    x: x,
    y: y,
    coordinateUnit: CoordinateUnit.level,
  );
}

// Helper operate to create a DecoratedBox with textual content
Widget createDecoratedBox(String textual content, Coloration borderColor, Coloration colour) {
  return Middle(
    baby: DecoratedBox(
      .....
    ),
  );
}

// Perform to create an inventory of annotations
Listing<CartesianChartAnnotation> _createAnnotations() {
  TextStyle textStyle = TextStyle(fontSize: 18, colour: Colours.white);
  return<CartesianChartAnnotation>[
    _createAnnotation(
      SfCircularChart(
        series:<CircularSeries>[
          DoughnutSeries<ChartData, String>(
            dataSource: [
              ChartData('Example', 40, Colors.black54),
              ChartData('Example', 25, Colors.red.withOpacity(0.7)),
            ],
            xValueMapper: (ChartData information, int index) => information.x,
            yValueMapper: (ChartData information, int index) => information.y,
            pointColorMapper: (ChartData information, int index) => information.colour,
          ),
        ],
      ),
      '1969',
      156,
    ),
    _createAnnotation(
      Textual content(
        "Coal consumption throughout nthe world from 1965 to 2023.",
        type: TextStyle(fontSize: 18, fontWeight: FontWeight.daring),
      ),
      '1976',
      156,
    ),
    // Knowledge label annotations on collection.
    _createAnnotation(Textual content("Europe", type: textStyle), '1986', 10),
    _createAnnotation(Textual content("Relaxation Of World", type: textStyle), '1995', 24),
    _createAnnotation(Textual content("North America", type: textStyle), '2002', 40),
    _createAnnotation(Textual content("Asia Pacific", type: textStyle), '2010', 83),

    // Knowledge label annotations on the fringe of the collection.
    _createAnnotation(
      createDecoratedBox('$asiaPacific', Colours.crimson, Colours.crimson.shade100),
      '2022',
      167,
    ),
    _createAnnotation(
      createDecoratedBox('$northAmerica', Colours.blue, Colours.blue.shade100),
      '2022',
      36,
    ),
    _createAnnotation(
      createDecoratedBox('$restOfWorld', Colours.inexperienced, Colours.inexperienced.shade100),
      '2022',
      24,
    ),
    _createAnnotation(
      createDecoratedBox('$europe', Colours.yellow, Colours.yellow.shade100),
      '2022',
      14,
    ),
  ];
}

Confer with the next picture.

Visualizing the coal consumption in various regions using Flutter Stacked Area Chart
Visualizing the coal consumption in varied areas utilizing Flutter Stacked Space Chart

GitHub reference

For extra particulars, check with the visualizing world coal consumption tendencies utilizing the Flutter Stacked Space Chart.

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

Attempt It Free

Conclusion

Thanks for studying! This weblog explains visualize the worldwide coal consumption pattern utilizing the Syncfusion Flutter Stacked Space Chart. We hope these steps enable you simply create the same visualization and improve your information illustration.

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

For questions, you possibly can contact us by means of our assist boardsassist portal, or suggestions portal. We’re at all times glad to help you!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments