We have updated WebDataRocks EULA, effective as of April 18, 2024. Learn more about what's changed.
Documentation menu

Integration with amCharts

This step-by-step guide will help you integrate WebDataRocks with amCharts. 

Starting from the 1.3.1 version, WebDataRocks supports integration with amCharts – a high-level JavaScript library for interactive data visualization. 

This tutorial is based on the V4 of amCharts. 

The guide consists of the following sections:

The integration can be done via a special connector – a JavaScript file that provides API for interaction between WebDataRocks and amCharts. See more details on the Connector’s API calls and principles of work in the API reference.

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:

[{
    "categoryName": "value",
    "measureName1": "value",
    ...
    "measureNameN": "value",
}, 
 ...
 
]

Any chart type that accepts such data format will work with WebDataRocks Pivot Table.

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

How to integrate WebDataRocks with amCharts

The steps below cover how summarized data from WebDataRocks can be passed to a column chart. For other chart types, refer to the examples above or to the amCharts documentation.

Step 1: Create a pivot table and configure the report

Following the instructions from the Quick start guide, initialize the pivot table on the page and connect it to the data source (JSON or CSV) as in the code snippet below:

<link href="https://cdn.webdatarocks.com/latest/webdatarocks.min.css" rel="stylesheet" />
<script src="https://cdn.webdatarocks.com/latest/webdatarocks.js"></script>
<div id="pivotContainer"></div>
<script>
    var pivot = new WebDataRocks({
        container: "#pivotContainer",
        toolbar: true,
        height: 580,
        width: "100%",
        report: {
            "dataSource": {
                "dataSourceType": "csv",
                "filename": "https://cdn.webdatarocks.com/data/data.csv"
            },
            "slice": {
                "rows": [{
                    "uniqueName": "Country"
                }],
                "columns": [{
                    "uniqueName": "Measures"
                }],
                "measures": [{
                    "uniqueName": "Price",
                    "aggregation": "sum"
                }]
            }
        }
    });
</script>

Note that we set the slice that specifies which fields go to the rows, columns, and measures. Find more details on what the slice is and how to set it in the pivot table.

Step 2: Connect to amCharts

  1. Include amCharts JS files:
    <script src="https://www.amcharts.com/lib/4/core.js"></script>
    <script src="https://www.amcharts.com/lib/4/charts.js"></script>
    <script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
    

    Find more information about other ways of amCharts installation in the official amCharts documentation

  2. Include WebDataRocks Connector for amCharts:
    <script src="https://cdn.webdatarocks.com/latest/webdatarocks.amcharts.js"></script>
    

Step 3: Create a chart

  1. Create a container for the chart:
    <div id="chartContainer"></div> 
  2. The chart should be created only after the pivot table is ready to provide the aggregated data. To track this, add an event handler for reportcomplete:
    var pivot = new WebDataRocks({
    container: "#pivotContainer",
    toolbar: true,
    height: 580,
    width: "100%",
    report: {
    // the report is the same as in the Step 1
    },
    reportcomplete: function() {
    pivot.off("reportcomplete");
    createChart();
    }

    });

    Once this event is triggered, the createChart() function will be invoked. Its description will be given below.

  3. Declare a variable for the chart:
    var chart;

    Note that the variable should be accessible by the functions that draw and redraw the chart. 

  4. In createChart(), request the data from the pivot table using the webdatarocks.amcharts.getData() method:
    function createChart() {
    pivot.amcharts.getData({}, drawChart, updateChart);
    }

    Note that the returned data is structured according to a format required by amCharts.The requested data contains the fields defined by the current slice of the pivot table. If the slice is passed as an argument to webdatarocks.amcharts.getData(), the data is prepared accordingly to it.

  5. Define drawChart() specified in the previous step – a function that initializes the chart, sets all the configurations specific for this chart type, and fills it with the data provided by WebDataRocks via the webdatarocks.amcharts.getData() API call. Pass this function as a callbackHandler to webdatarocks.amcharts.getData():
    function drawChart(chartData, rawData) {
    /* Create a chart instance */
    chart = am4core.create("chartContainer", am4charts.XYChart);
    /* Add data processed by WebDataRocks to the chart */
    chart.data = chartData.data;
    /* Create category axis */
    var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
    categoryAxis.dataFields.category = pivot.amcharts.getCategoryName(rawData);
    / * Create value axis * /
    var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
    / * Create and configure series * /
    var series = chart.series.push(new am4charts.ColumnSeries());
    series.dataFields.categoryX = pivot.amcharts.getCategoryName(rawData);
    series.dataFields.valueY = pivot.amcharts.getMeasureNameByIndex(rawData, 0);
    }

    The lines of code that are highlighted in bold are related to the interaction between the pivot table and charts. Let’s break down what they stand for. After passing the data from the pivot table to the chart, set a name of the category to the category axis:

    categoryAxis.dataFields.category = pivot.amcharts.getCategoryName(rawData); 

    For this, the webdatarocks.amcharts.getCategoryName() method is used. It returns the name of the category of the prepared data. By default, it’s a caption of the first hierarchy from the rows. If the rows do not contain fields, webdatarocks.amcharts.getCategoryName() returns a caption of the first hierarchy from the columns.The same method is used for setting the chart’s category to the series:

    series.dataFields.categoryX = webdatarocks.amcharts.getCategoryName(rawData); 

    To set the series values, the webdatarocks.amcharts.getMeasureNameByIndex() method is used:

    series.dataFields.valueY = webdatarocks.amcharts.getMeasureNameByIndex(rawData, 0);

    Find more details on the API calls available in the Connector for amCharts in the API reference.

  6. Define a function that redraws the chart once any change is applied to the pivot table’s report (e.g., the data is filtered, sorted, the formatting is changed, etc). Pass this function as an updateHandler to webdatarocks.amcharts.getData():

    function updateChart(chartData, rawData) {
    chart.dispose();
    drawChart(chartData, rawData);
    }

    Upon update, the existing chart will be disposed of. Next, the process described in drawChart is repeated, namely drawing the chart but with updated data, its slice, or formatting.

Step 4: See the results

Here is the example of the resulting dashboard with the chart reacting to changes in the slice of the pivot table. It is possible to add more different charts if needed.

See the Pen amCharts column chart minimal configuration and Pivot Table by WebDataRocks (@webdatarocks) on CodePen.

How to set number formatting to the chart

It can be important to display the data in the charts the same way as it comes from the pivot grid.

WebDataRocks Connector for amCharts provides a method that can take a Format Object from WebDataRocks and convert it to the amCharts number formatting pattern:

webdatarocks.amcharts.getNumberFormatPattern(format: Object)

This method can be used for applying formatting to the chart’s axes or to the tooltip.

When the formatting string is prepared by the method, the following properties of the pivot table’s format object are considered:

  • thousandsSeparator
  • decimalSeparator
  • decimalPlaces
  • maxDecimalPlaces
  • currencySymbol
  • currencySymbolAlign
  • isPercent

Here’s an example of the formatting string returned by the method:

$#,###.00

Examples

1) How to apply number formatting to the value axis:

/* Create a number formatter for the value axis: */
valueAxis.numberFormatter = new am4core.NumberFormatter();
/* Get a format object from WebDataRocks: */
var numberFormat = pivot.amcharts.getNumberFormatPattern(rawData.meta.formats[0]);
/* Apply number formatting to the value axis: */
valueAxis.numberFormatter.numberFormat = numberFormat; 

In this case, the first format object from the report’s configuration is returned. By accessing the format by index from rawData, it’s possible to retrieve any format object and process it by this method.

2) How to format values on the chart’s tooltip:

series.columns.template.tooltipText = "{valueY.value.formatNumber('" + numberFormat + "')}";

Dashboard with WebDataRocks and amCharts sample

This sample shows how to integrate WebDataRocks with amCharts and create a dashboard:

See the Pen amCharts Donut Chart & WebDataRocks Pivot Table by WebDataRocks (@webdatarocks) on CodePen.

See also