Integration with amCharts

This step-by-step tutorial will help you integrate WebDataRocks with amCharts. Our tutorial is based on the V4 of amCharts.

Supported chart types

WebDataRocks Connector for amCharts takes the data from the pivot table and prepares it according to the structure of an array of objects required by amCharts. As a result, any chart type will work with WebDataRocks Pivot Table.

Here is the list of demos that show how to integrate different chart types with WebDataRocks:

  • Column Chart (demo)
  • Line Chart (demo)
  • Stacked Column Chart (demo)
  • Bar Chart (demo)
  • Clustered Bar Chart (demo)
  • Stacked Bar Chart (demo)
  • Radar Chart (demo)
  • Bubble Chart (demo)
  • Pie Chart (demo)
  • Semi-circle Pie Chart (demo)
  • Donut Chart (demo)
  • Nested Donut Chart (demo)
  • Radar Chart with switched axes (demo)

Follow the steps below to start creating interactive data visualizations.

Step 1. Add WebDataRocks to your project

Step 1.1. Complete the Quick start guide. Your code of the component with WebDatarocks should look similar to the following:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    }
    <app-wbr-pivot
     [toolbar]="true">
    </app-wbr-pivot>

    Step 1.2. Create a report for WebDataRocks — connect to the data source and define which fields should be displayed in rows, columns, and measures:

      import { Component} from "@angular/core";
      
      @Component({
        selector: "app-root",
        templateUrl: "./app.component.html",
        styleUrls: ["./app.component.css"],
      })
      export class AppComponent {
        report = {
          dataSource: {
            filename: "https://cdn.webdatarocks.com/data/data.csv",
          },
          slice: {
            rows: [
              {
                uniqueName: "Country",
              },
            ],
            columns: [
              {
                uniqueName: "Measures",
              },
            ],
            measures: [
              {
                uniqueName: "Price",
                aggregation: "sum",
              },
            ],
          },
        };
      }
      <app-wbr-pivot
       [toolbar]="true"
       [report]="report">
      </app-wbr-pivot>

      The fields you’ve specified in the report will be shown on the chart.

      Step 2. Get a reference to the WebDataRocks instance

      Some of WebDataRocks methods and events are needed to create a chart. Using a reference to the WebDataRocks instance, we can access WebDataRocks API.

      Import WebdatarocksComponent and get a reference to the <app-wbr-pivot> instance using a template variable and the @ViewChild decorator:

        import { Component, ViewChild } from "@angular/core";
        import { WebdatarocksComponent } from "@webdatarocks/ngx-webdatarocks";
        
        @Component({
          selector: "app-root",
          templateUrl: "./app.component.html",
          styleUrls: ["./app.component.css"],
        })
        export class AppComponent {
          @ViewChild("pivot") pivotRef!: WebdatarocksComponent;
        
          // ...
        }
        <app-wbr-pivot #pivot
         [toolbar]="true"
         [report]="report">
        </app-wbr-pivot>

        Now it’s possible to interact with the component through this.pivotRef.webdatarocks.

        Note. If you are using the legacy @webdatarocks/ng-webdatarocks wrapper, import WebdatarocksComponent from it.

        Step 3. Add amCharts

        Step 3.1. Install the amCharts 4 npm package with the following command:

        npm install @amcharts/amcharts4

        Step 3.2. Import amCharts into your component:

          import * as am4core from '@amcharts/amcharts4/core';
          import * as am4charts from '@amcharts/amcharts4/charts';
          import am4themes_animated from '@amcharts/amcharts4/themes/animated';
          
          // Apply the imported theme
          am4core.useTheme(am4themes_animated);

          Step 3.3. In the HTML template of the component, add a <div> container for your chart:

            <app-wbr-pivot #pivot
             [toolbar]="true"
             [report]="report">
            </app-wbr-pivot>
            <div id="amcharts-container" style="width: 100%; height: 300px"></div>

            Step 3.4. Create a variable that will store a chart instance:

              chart!: am4charts.XYChart;

              Step 3.5. In your package.json file, add --prod --build-optimizer=false flags to the "build" script to disable the build optimizer:

              "scripts": {
              // ...
              "build": "ng build --prod --build-optimizer=false",
              // ...
              },

              Step 4. Show the data from the pivot table on the chart

              Step 4.1. Import the WebDataRocks Connector for amCharts:

                import "@webdatarocks/webdatarocks/webdatarocks.amcharts.js";

                The Connector provides the amcharts.getData() method, which gets data from WebDataRocks and converts it to the format required by amCharts.

                Step 4.2. If we call the amcharts.getData() method before WebDataRocks is fully loaded and ready to use, it will return an empty result. To know when WebDataRocks is ready to provide data for the chart, handle the reportcomplete event:

                  onReportComplete() {
                    // Unsubscribing from reportcomplete
                    // We need it only to track the initialization of WebDataRocks
                    this.pivotRef.webDataRocks.off("reportComplete");
                    this.createChart();
                  }
                  <app-wbr-pivot #pivot
                   [toolbar]="true"
                   [report]="report"
                   (reportcomplete)="onReportComplete()">
                  </app-wbr-pivot>

                  Now we know when the data is loaded and the report is ready.

                  Step 4.3. Implement the createChart() function. This function will use the amcharts.getData() method from the Connector:

                    createChart() {
                      this.pivotRef.webDataRocks.amcharts?.getData(
                        {},
                        // Function called when data for the chart is ready
                        this.drawChart.bind(this),
                        // Function called on report changes (filtering, sorting, etc.) 
                        this.drawChart.bind(this)
                      );
                    }

                    Step 4.4. Implement the drawChart() function from the previous step. drawChart() initializes the chart, sets all the configurations specific for this chart type, and fills it with the data provided by WebDataRocks:

                      drawChart(chartConfig: any, rawData: any) {
                        // Create chart instance
                        // The selector must match the id of the <div> container for the chart
                        let chart = am4core.create("amcharts-container", am4charts.XYChart);
                      
                        // Add data processed by Flexmonster to the chart
                        chart.data = chartConfig.data;
                      
                        // Create a category axis for a column chart
                        let categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
                        categoryAxis.dataFields.category = this.pivotRef.webDataRocks.amcharts?.getCategoryName(rawData);
                        // Create value axis
                        chart.yAxes.push(new am4charts.ValueAxis());
                        // Create and configure series
                        let series = chart.series.push(new am4charts.ColumnSeries());
                        series.dataFields.categoryX = this.pivotRef.webDataRocks.amcharts?.getCategoryName(rawData);
                        series.dataFields.valueY = this.pivotRef.webDataRocks.amcharts?.getMeasureNameByIndex(rawData, 0);
                      
                        this.chart = chart;
                      }

                      Learn more about the amcharts.getCategoryName() and amcharts.getMeasureNameByIndex() API calls.

                      Step 4.5. Set the autoDispose global option to true. As a result, the chart will be automatically disposed when it is necessary:

                        am4core.useTheme(am4themes_animated);
                        am4core.options.autoDispose = true;

                        Step 5. Run the project

                        Run your project with the following command:

                        ng serve --open

                        Open http://localhost:4200/ in the browser to see how the pivot table looks in combination with amCharts.

                        To see what a real-time interaction is, try experimenting: filter the data, change the measures and the aggregation functions — the results are reflected on the chart at once.

                        Learn more about available chart configurations in the amCharts Documentation.

                        Check out the full code

                        After completing this tutorial, the full code of the integration should look as follows:

                          import { Component, ViewChild } from '@angular/core';
                          import { WebdatarocksComponent } from "@webdatarocks/ngx-webdatarocks";
                          
                          import * as am4core from '@amcharts/amcharts4/core';
                          import * as am4charts from '@amcharts/amcharts4/charts';
                          import am4themes_animated from '@amcharts/amcharts4/themes/animated';
                          
                          import "@webdatarocks/webdatarocks/webdatarocks.amcharts.js";
                          
                          am4core.useTheme(am4themes_animated);
                          am4core.options.autoDispose = true;
                          
                          @Component({
                            selector: 'app-root',
                            templateUrl: './app.component.html',
                            styleUrl: './app.component.css'
                          })
                          export class AppComponent {
                            @ViewChild('pivot') pivotRef!: WebdatarocksComponent;
                            chart!: am4charts.XYChart;
                          
                            report = {
                              dataSource: {
                                filename: "https://cdn.webdatarocks.com/data/data.csv",
                              },
                              slice: {
                                rows: [
                                  {
                                    uniqueName: "Country",
                                  },
                                ],
                                columns: [
                                  {
                                    uniqueName: "Measures",
                                  },
                                ],
                                measures: [
                                  {
                                    uniqueName: "Price",
                                    aggregation: "sum",
                                  },
                                ],
                              },
                            };
                          
                            onReportComplete() {
                              this.pivotRef.webDataRocks.off("reportcomplete");
                              this.createChart();
                            }
                          
                            createChart() {
                              this.pivotRef.webDataRocks.amcharts?.getData(
                                {},
                                this.drawChart.bind(this),
                                this.drawChart.bind(this)
                              );
                            }
                          
                            drawChart(chartConfig: any, rawData: any) {
                              let chart = am4core.create("amcharts-container", am4charts.XYChart);
                          
                              chart.data = chartConfig.data;
                          
                              let categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
                              categoryAxis.dataFields.category = this.pivotRef.webDataRocks.amcharts?.getCategoryName(rawData);
                              chart.yAxes.push(new am4charts.ValueAxis());
                              let series = chart.series.push(new am4charts.ColumnSeries());
                              series.dataFields.categoryX = this.pivotRef.webDataRocks.amcharts?.getCategoryName(rawData);
                              series.dataFields.valueY = this.pivotRef.webDataRocks.amcharts?.getMeasureNameByIndex(rawData, 0);
                            
                              this.chart = chart;
                            } 
                          }
                          <app-wbr-pivot #pivot
                           [toolbar]="true"
                           [report]="report"
                           (reportcomplete)="onReportComplete()">
                          </app-wbr-pivot>
                          <div id="amcharts-container" style="width: 100%; height: 300px"></div>

                          See also