Need a special offer?Find out if your project fits.
+
  1. API reference
  • Introduction
  • Connecting to Data Source
  • Browser compatibility
  • Documentation for older versions
  • Table of contents

    Integration with amCharts

    This tutorial shows how to integrate Flexmonster with amCharts — a JavaScript library for interactive data visualization. Flexmonster supports amCharts 5 and amCharts 4.

    Watch the tutorial in the video format: Pivot table with amCharts.

    This guide contains the following sections:

    Supported chart types

    Flexmonster supports all chart types available in amCharts 5 and amCharts 4.

    Visit the Examples page for ready-to-use examples of integration with different chart types.

    Adding amCharts

    The steps below describe how to create a pie chart based on data received from the component. To integrate Flexmonster with other chart types, refer to the amCharts documentation.

    Step 1. Embed the component into your webpage

    Add Flexmonster to your webpage and configure a simple report (e.g., based on a JSON or CSV data source). Replace "XXXX-XXXX-XXXX-XXXX-XXXX" with your license key. If you don’t have a license key, contact our team and request a special trial key.

    <div id="pivotContainer">The component will appear here</div>
    <script src="https://cdn.flexmonster.com/flexmonster.js"></script>
    
    <script>
      const pivot = new Flexmonster({
        container: "pivotContainer",
        componentFolder: "https://cdn.flexmonster.com/",
        report: {
          dataSource: {
            filename: "data/data.csv"
          },
          slice: {
            rows: [
              { uniqueName: "Country" }
            ],
            columns: [
              { uniqueName: "Color" },
              { uniqueName: "[Measures]" }
            ],
            measures: [
              { uniqueName: "Price" }
            ]
          }
        },
        licenseKey: "XXXX-XXXX-XXXX-XXXX-XXXX"
      });
    </script>

    Step 2. Add amCharts files

    Include the amCharts files to your webpage:

    amCharts 5

    <script src="https://cdn.amcharts.com/lib/5/index.js"></script>
    <script src="https://cdn.amcharts.com/lib/5/percent.js"></script>

    Including files directly to the webpage is one of the possible ways to add amCharts. Refer to the amCharts installation guide for other ways of adding amCharts 5.

    amCharts 4

    <script src="https://cdn.amcharts.com/lib/4/core.js"></script>
    <script src="https://cdn.amcharts.com/lib/4/charts.js"></script>

    Including files directly to the webpage is one of the possible ways to add amCharts. Refer to the amCharts installation guide for other ways of adding amCharts 4.

    Step 3. Add Flexmonster Connector for amCharts

    Flexmonster Connector for amCharts provides ready-to-use methods for easy and smooth integration with amCharts. Add it to your webpage with the following line of code:

    <script src="https://cdn.flexmonster.com/lib/flexmonster.amcharts.js"></script> 

    Step 4. Add a container for amCharts

    Add a container for the chart:

    <div id="chartContainer"></div>

    Note If you are integrating with amCharts 5, explicitly set the height for your container in CSS styles. Otherwise, the created chart will not be visible.

    Step 5. Add a reportcomplete event handler

    A chart should be created only when the component is ready to provide the data. To track this, use the reportcomplete event:

    const pivot = new Flexmonster({
      container: "pivotContainer",
      componentFolder: "https://cdn.flexmonster.com/",
      report: {
        // Report from the 1st step
      },
      licenseKey: "XXXX-XXXX-XXXX-XXXX-XXXX",
      reportcomplete: function() {
        pivot.off("reportcomplete");
        createChart();
      }
    });  

    When data loading is complete, the event handler will invoke the createChart() function to draw the chart. The implementation of the createChart() function is given below.

    Step 6. Request data from the component

    The Connector for amCharts provides the amcharts.getData() method, which requests data from the component and returns it as an array of objects. Call the amcharts.getData() method to get data from the component:

    function createChart() {
      pivot.amcharts.getData({}, drawChart, updateChart);
    }

    Data returned by the amcharts.getData() method contains fields specified in the report.slice object. If the amcharts.getData() method gets a slice as a parameter, the data is prepared according to it.

    Step 7. Create a global variable to work with the chart instance

    Declare a global variable that will be used to draw and update the chart:

    amCharts 5

    In amCharts 5, charts should be created in a root element. Create the root element in the container we have added in step 4:

    const root = am5.Root.new("chartContainer");

    amCharts 4

    Create an empty variable:

    let chart;

    It will be initialized later in the function that draws the chart.

    Step 8. Create a function to draw the chart

    The drawChart() function initializes the chart, configures it, and fills the chart with data provided by the amcharts.getData() method:

    amCharts 5

    function drawChart(chartConfig, rawData) {
      // Create the chart
      let chart = root.container.children.push(
        am5percent.PieChart.new(root, {})
      );
    
      // Create and configure pie series
      let series = chart.series.push(
        am5percent.PieSeries.new(root, {
          valueField: pivot.amcharts.getMeasureNameByIndex(rawData, 0),
          categoryField: pivot.amcharts.getCategoryName(rawData),
         })
      );
      series.slices.template.setAll({
        stroke: am5.color("#fff"),
        strokeWidth: 2,
      });
      series.labels.template.setAll({
        fontSize: 12
      });
    
      // Fill the chart with the data from Flexmonster
      series.data.setAll(chartConfig.data);
    }

    Notice the following lines in the code snippet:

    am5percent.PieSeries.new(root, {
      categoryField: pivot.amcharts.getCategoryName(rawData),
      valueField: pivot.amcharts.getMeasureNameByIndex(rawData, 0),
    });

    The amcharts.getCategoryName() method is used to set the categoryField for the pie series. Learn more about how the method chooses the category.

    Then, amcharts.getMeasureNameByIndex() sets the valueField.

    For more details on how the pie chart is created, see the amCharts documentation.

    amCharts 4

    function drawChart(chartData, rawData) {
      // Initialize the chart
      chart = am4core.create("chartContainer", am4charts.PieChart);
    
      // Fill the chart with the data from Flexmonster
      chart.data = chartData.data;
    
      // Create and configure pie series
      let series = chart.series.push(new am4charts.PieSeries());
      series.dataFields.category = pivot.amcharts.getCategoryName(rawData);
      series.dataFields.value = pivot.amcharts.getMeasureNameByIndex(rawData, 0);
      series.slices.template.stroke = am4core.color("#fff");
      series.slices.template.strokeWidth = 2;
      series.labels.template.fontSize = 12;
    }

    Notice the following lines in the code snippet:

    series.dataFields.category = pivot.amcharts.getCategoryName(rawData);
    series.dataFields.value = pivot.amcharts.getMeasureNameByIndex(rawData, 0);

    The amcharts.getCategoryName() method is used to set the category name for the amCharts Category axis. Learn more about how the method chooses the category name.

    Then, amcharts.getMeasureNameByIndex() sets the value for the Value axis.

    For more details on how the pie chart is created, see the amCharts documentation.

    Step 9. Create a function to update the chart

    Create a function that will redraw the chart once the report is updated (e.g., when the data is filtered, sorted, etc.):

    amCharts 5

    function updateChart(chartConfig, rawData) {
      root.container.children.clear();
      drawChart(chartConfig, rawData);
    }

    amCharts 4

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

    When the data is updated, this function will redraw the chart based on the updated data.

    Step 10. See the results

    Launch your webpage from a browser and see an interactive pie chart displaying data from the component. Check out a live example on JSFiddle:

    You can also watch our video tutorial that covers the integration process:

    Preparing data for the chart

    This section explains how Flexmonster Connector for amCharts preprocesses data for the chart.

    The amcharts.getData() method returns data as a JSON array of objects:

    [
      {
        "categoryName": "value",
        "measureName 1": "value",
        …
        "measureName n": "value",
      }
      …
    ]

    Each object in the array contains only one category field as well as all the measures from the slice.

    A field to represent the category is chosen as follows:

    1. If the slice.rows array contains some fields, the first field from rows is chosen to be the category.
    2. If the slice.rows array is empty and the slice.columns array contains some fields, the first field from columns is chosen as the category.

    If both slice.rows and slice.columns are empty, then no category is available, and amcharts.getCategoryName() will return undefined.

    In such cases, the amcharts.getMeasureNameByIndex() method can be used to select the category for the series.

    Flexmonster Connector for amCharts

    flexmonster.amcharts.js is a connector between the Flexmonster component and amCharts. Learn more about the Connector’s API.

    Defining number formatting for amCharts

    The Connector allows defining number formatting for amCharts using the amcharts.getNumberFormatPattern() method, which converts the FormatObject to the amCharts number formatting string.

    This method considers the following FormatObject properties:

    • decimalPlaces
    • maxDecimalPlaces
    • negativeNumberFormat (only the -1 and (1) formats are available)
    • currencySymbol
    • positiveCurrencyFormat
    • negativeCurrencyFormat (only the $-1, -1$, ($1), (1$) formats are available)
    • isPercent

    Regardless of the FormatObject configuration, the following properties have constant values in amCharts:

    • thousandsSeparator: ","
    • decimalSeparator: "."

    Note amCharts imposes this limitation because it uses predefined separators for decimals and thousands.

    Example

    The following example demonstrates how the FormatObject is converted to the amCharts number formatted string.

    Take a look at the following format:

    report: {
      formats: [{
        name: "currency",
        decimalPlaces: 2,
        maxDecimalPlaces: 2,
        negativeNumberFormat: '-1',
        currencySymbol: '$',
        positiveCurrencyFormat: '$1',
        negativeCurrencyFormat: '($1)',
        isPercent: false 
      }],
      measures: [{
        uniqueName: "Price",
        format: "currency"
      }]
    };

    The amcharts.getNumberFormatPattern() method converts this format to the following string: '$'#,###.00|'($'#,###.00s')'. The string consists of two parts separated by '|':

    1. '$'#,###.00 defines how positive numbers are formatted. For example, 1205 will be shown as $1,205.00.
    2. '($'#,###.00's)' defines how negative numbers are formatted. s is a part of the amCharts format pattern that returns the absolute value (without - sign). For example, -1205 will be shown as ($1,205.00).

    Applying number formatting to amCharts

    Number formatting can be applied both to amCharts 5 and to amCharts 4.

    amCharts 5

    To apply number formatting to the root element, use the numberFormatter.set() method:

    root = am5.Root.new("amcharts-container");
    
    // Prepare number formatting from Flexmonster to a format required by amCharts
    let numberFormat = pivot.amcharts.getNumberFormatPattern(rawData.meta.formats[0]);
    
    // Apply number formatting to the chart 
    root.numberFormatter.set("numberFormat", numberFormat);

    Check out this example on JSFiddle.

    amCharts 4

    To apply number formatting to a specific axis, use the NumberFormatter.numberFormat property.

    let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
    
    // Prepare number formatting from Flexmonster to a format required by amCharts
    let numberFormat = pivot.amcharts.getNumberFormatPattern(rawData.meta.formats[0]);
    valueAxis.numberFormatter = new am4core.NumberFormatter();
    
    // Apply number formatting to the chart
    valueAxis.numberFormatter.numberFormat = numberFormat;

    See an example on JSFiddle.

    What's next?