Get Free Trial
List of all demos

JavaScript Pivot Table with amCharts

Flexmonster Pivot Table & Charts seamlessly integrates with amCharts — a programming visualization library with super interactive charts.

Thanks to our chart connector, your visualizations will become even more interactive: as soon as you change the slice on the pivot or filter the data, your charts will immediately transform.

Overall Cheese Interest by Month

Creating dashboards with amCharts and Flexmonster Pivot Grid is easy and enjoyable: you can choose from a wide range of different modern and bright charts to effectively visualize your data and present it in the most favorable way.

Total Cheese Interest by Country
Icons made by Freepik from www.flaticon.com

Simply configure JS pivot grid with the data you need and instantly submit all the information to interactive charts to highlight the essential points and quickly identify all extremes.

Feta Interest by Month
Feta Interest by Country

    let pivot = new Flexmonster({
      container: "pivot-container",
      licenseFilePath: "https://cdn.flexmonster.com/jsfiddle.charts.key",
      componentFolder: "https://cdn.flexmonster.com/",
      height: 440,
      customizeCell: customizeCell,
      report: {
        dataSource: {
          filename: "data/demos/amcharts-demo-data.json",
          mapping: {
            "Date": {
              type: "date"
            },
            "Country": {
              type: "string"
            },
            "id": {
              type: "string"
            },
            "CountryCode": {
              type: "property",
              hierarchy: "Country"
            },
            "Feta": {
              type: "number"
            },
            "Mozzarella": {
              type: "number"
            },
            "Parmigiano-Reggiano": {
              type: "number"
            }
          }
        },
        "slice": {
          "rows": [{
              "uniqueName": "Date.Month",
              "filter": {
                "exclude": [
                  "date.month.[december]",
                  "date.month.[november]",
                  "date.month.[october]"
                ]
              }
            },
            {
              "uniqueName": "[Measures]"
            }
          ],
          "columns": [{
            "uniqueName": "Country"
          }],
          "measures": [{
              "uniqueName": "Feta",
              "aggregation": "sum",
              "grandTotalCaption": "Feta"
            },
            {
              "uniqueName": "Mozzarella",
              "aggregation": "sum",
              "grandTotalCaption": "Mozzarella"
            },
            {
              "uniqueName": "Parmigiano-Reggiano",
              "aggregation": "sum",
              "grandTotalCaption": "Parmigiano-Reggiano"
            }
          ]
        },
        "options": {
          "grid": {
            "showHeaders": false,
            "showGrandTotals": "rows"
          },
          "showAggregationLabels": false
        }
      },
      reportcomplete: function() {
        pivot.off("reportcomplete");
        createPieChart();
        createStackedChart();
        createMapChart();
        createPictorialChart();
      }
    });
    
    let mapChart, pieChart, stackedChart, pictorialChart;
    // Apply amCharts theme
    am4core.useTheme(am4themes_animated);
    
    const chartColors = [
      am4core.color("#4CBF8B"),
      am4core.color("#FFCD4C"),
      am4core.color("#E8734C"),
      am4core.color("#9875E3"),
      am4core.color("#4C9EFF"),
      am4core.color("#8ACFC3"),
      am4core.color("#CD97E6"),
      am4core.color("#F1D34C"),
      am4core.color("#65D2E7"),
    ];
    
    const cheeseColors = [
      am4core.color("#FFE268"),
      am4core.color("#FFCD4C"),
      am4core.color("#FFB037")
    ];
    
    function createPieChart() {
      pivot.amcharts.getData({
        "slice": {
          "rows": [{
            "uniqueName": "Date.Month",
            "filter": {
              "members": [
                "date.month.[january]",
                "date.month.[february]",
                "date.month.[march]",
                "date.month.[april]",
                "date.month.[may]",
                "date.month.[june]"
              ]
            }
          }],
          "measures": [{
            "uniqueName": "Feta",
            "aggregation": "sum"
          }]
        }
      }, drawPieChart, updatePieChart);
    }
    
    function drawPieChart(chartData, rawData) {
      // initialize the chart
      pieChart = am4core.create("amcharts-pie-container", am4charts.PieChart);
      //fill the chart with the data from Flexmonster
      pieChart.data = chartData.data;
      let numberFormat = pivot.amcharts.getNumberFormatPattern(rawData.meta.formats[0]);
      pieChart.numberFormatter.numberFormat = numberFormat;
      // Create pie series
      let series = pieChart.series.push(new am4charts.PieSeries());
      series.dataFields.value = pivot.amcharts.getMeasureNameByIndex(rawData, 0);
      series.dataFields.radiusValue = pivot.amcharts.getMeasureNameByIndex(rawData, 0);
      series.dataFields.category = pivot.amcharts.getCategoryName(rawData);
      series.slices.template.cornerRadius = 6;
      series.slices.template.stroke = am4core.color("#fff");
      series.slices.template.strokeWidth = 2;
      series.slices.template.strokeOpacity = 1;
      series.hiddenState.properties.endAngle = -90;
      pieChart.legend = new am4charts.Legend();
      pieChart.responsive.enabled = true;
      pieChart.responsive.rules.push({
        relevant: function(target) {
          if (target.pixelWidth <= 600) {
            return true;
          }
          return false;
        },
        state: function(target, stateId) {
          if (target instanceof am4charts.PieSeries) {
            var state = target.states.create(stateId);
    
            var labelState = target.labels.template.states.create(stateId);
            labelState.properties.disabled = true;
    
            var tickState = target.ticks.template.states.create(stateId);
            tickState.properties.disabled = true;
            return state;
          }
          return null;
        }
      });
      series.colors.list = chartColors;
    }
    
    function updatePieChart(chartData, rawData) {
      // Here you can add your own logic for updating the chart
    }
    
    function createStackedChart() {
      pivot.amcharts.getData({}, drawStackedChart, updateStackedChart);
    }
    
    function drawStackedChart(chartData, rawData) {
      // Create chart instance
      stackedChart = am4core.create("amcharts-stacked-container", am4charts.XYChart);
    
      stackedChart.marginRight = 400;
    
      // Add data
      stackedChart.data = chartData.data;
      stackedChart.colors.list = chartColors;
    
      // Create axes
      var categoryAxis = stackedChart.xAxes.push(new am4charts.CategoryAxis());
      categoryAxis.dataFields.category = pivot.amcharts.getCategoryName(rawData);
      categoryAxis.renderer.grid.template.location = 0;
      categoryAxis.renderer.minGridDistance = 20;
    
      // Configure axis label
      var label = categoryAxis.renderer.labels.template;
      label.truncate = true;
      label.maxWidth = 200;
      label.tooltipText = "{category}";
    
      categoryAxis.events.on("sizechanged", function(ev) {
        var axis = ev.target;
        var cellWidth = axis.pixelWidth / (axis.endIndex - axis.startIndex);
        if (cellWidth < axis.renderer.labels.template.maxWidth) {
          axis.renderer.labels.template.rotation = -45;
          axis.renderer.labels.template.horizontalCenter = "right";
          axis.renderer.labels.template.verticalCenter = "middle";
        } else {
          axis.renderer.labels.template.rotation = 0;
          axis.renderer.labels.template.horizontalCenter = "middle";
          axis.renderer.labels.template.verticalCenter = "top";
        }
      });
    
      var valueAxis = stackedChart.yAxes.push(new am4charts.ValueAxis());
      valueAxis.title.text = "Queries";
    
      for (let i = 0; i < pivot.amcharts.getNumberOfMeasures(rawData); i++) {
        // Create series
        var series = stackedChart.series.push(new am4charts.ColumnSeries());
        series.dataFields.valueY = pivot.amcharts.getMeasureNameByIndex(rawData, i);
        series.dataFields.categoryX = pivot.amcharts.getCategoryName(rawData);
        series.name = pivot.amcharts.getMeasureNameByIndex(rawData, i).split(" ").pop();
        series.tooltipText = "{name}: [bold]{valueY}[/]";
        series.stacked = true;
      }
    
      // Add cursor
      stackedChart.cursor = new am4charts.XYCursor();
    }
    
    function updateStackedChart(chartData, rawData) {
      stackedChart.dispose();
      drawStackedChart(chartData, rawData);
    }
    
    function createMapChart() {
      pivot.amcharts.getData({
        "slice": {
          "rows": [{
            "uniqueName": "id"
          }],
          "columns": [{
            "uniqueName": "[Measures]"
          }],
          "measures": [{
            "uniqueName": "Fetas",
            "formula": "sum(\"Feta\")",
            "caption": "value"
          }]
        },
      }, drawMapChart, updateMapChart);
    }
    
    function drawMapChart(chartData, rawData) {
      mapChart = am4core.create("amcharts-map-container", am4maps.MapChart);
      mapChart.hiddenState.properties.opacity = 0; // this creates initial fade-in
    
      mapChart.geodata = am4geodata_worldHigh;
      mapChart.projection = new am4maps.projections.Mercator();
    
      var polygonSeries = mapChart.series.push(new am4maps.MapPolygonSeries());
      var polygonTemplate = polygonSeries.mapPolygons.template;
      polygonTemplate.tooltipText = "{name} {value.value.formatNumber('#.0')}";
      polygonSeries.heatRules.push({
        property: "fill",
        target: polygonSeries.mapPolygons.template,
        min: am4core.color("#F1D34C"),
        max: am4core.color("#4CBF8B")
      });
      polygonSeries.useGeodata = true;
    
      // add heat legend
      var heatLegend = mapChart.chartContainer.createChild(am4maps.HeatLegend);
      heatLegend.valign = "bottom";
      heatLegend.align = "left";
      heatLegend.width = am4core.percent(100);
      heatLegend.series = polygonSeries;
      heatLegend.orientation = "horizontal";
      heatLegend.padding(20, 20, 20, 20);
      heatLegend.valueAxis.renderer.labels.template.fontSize = 10;
      heatLegend.valueAxis.renderer.minGridDistance = 40;
    
      polygonSeries.mapPolygons.template.events.on("over", event => {
        handleHover(event.target);
      });
    
      polygonSeries.mapPolygons.template.events.on("hit", event => {
        handleHover(event.target);
      });
    
      function handleHover(mapPolygon) {
        if (!isNaN(mapPolygon.dataItem.value)) {
          heatLegend.valueAxis.showTooltipAt(mapPolygon.dataItem.value);
        } else {
          heatLegend.valueAxis.hideTooltip();
        }
      }
    
      polygonSeries.mapPolygons.template.strokeOpacity = 0.4;
      polygonSeries.mapPolygons.template.events.on("out", event => {
        heatLegend.valueAxis.hideTooltip();
      });
    
      mapChart.homeZoomLevel = 9;
      mapChart.maxZoomLevel = 9;
      mapChart.minZoomLevel = 9;
      mapChart.homeGeoPoint = {
        longitude: 12.496366,
        latitude: 42.399982
      };
    
      polygonSeries.data = chartData.data;
    
      // excludes Antarctica
      polygonSeries.exclude = ["AQ"];
    }
    
    function updateMapChart(chartData, rawData) {
      // Here you can add your own logic for updating the chart
    }
    
    function createPictorialChart() {
      pivot.amcharts.getData({
        "slice": {
          "rows": [{
              "uniqueName": "Country"
            },
            {
              "uniqueName": "[Measures]"
            }
          ],
          "measures": [{
            "uniqueName": "Fetas",
            "formula": "sum(\"Feta\")",
            "caption": "value"
          }]
        }
      }, drawPictorialChart, updatePictorialChart);
    }
    
    function drawPictorialChart(chartData, rawData) {
    
      var iconPathValue = iconPath();
      pictorialChart = am4core.create("amcharts-pictorial-container", am4charts.SlicedChart);
      pictorialChart.hiddenState.properties.opacity = 0; // this makes initial fade in effect
    
      pictorialChart.data = chartData.data
    
      var series = pictorialChart.series.push(new am4charts.PictorialStackedSeries());
      series.colors.list = cheeseColors;
    
      series.dataFields.value = pivot.amcharts.getMeasureNameByIndex(rawData, 0);
      series.dataFields.category = pivot.amcharts.getCategoryName(rawData);
      series.alignLabels = true;
      series.labels = "disabled";
      series.ticks = "disabled";
    
      series.maskSprite.path = iconPathValue;
    
      pictorialChart.legend = new am4charts.Legend();
      pictorialChart.legend.position = "right";
      let marker = pictorialChart.legend.markers.template.children.getIndex(0);
      pictorialChart.legend.markers.template.width = 20;
      pictorialChart.legend.markers.template.height = 20;
      marker.cornerRadius(20, 20, 20, 20);
    
      pictorialChart.responsive.enabled = true;
      pictorialChart.responsive.rules.push({
        relevant: function(target) {
          if (target.pixelWidth <= 600) {
            return true;
          }
          return false;
        },
        state: function(target, stateId) {
          if (target instanceof am4charts.PictorialStackedSeries) {
            var state = target.states.create(stateId);
    
            var labelState = target.labels.template.states.create(stateId);
            labelState.properties.disabled = true;
    
            var tickState = target.ticks.template.states.create(stateId);
            tickState.properties.disabled = true;
            return state;
          }
          return null;
        }
      });
    }
    
    function updatePictorialChart(chartData, rawData) {
      // Here you can add your own logic for updating the chart
    }
    
    function customizeCell(cell, data) {
      if (data.hierarchy && data.type == "header") {
        if (data.hierarchy.caption == "Country" && data.member && data.member.properties) {
          let name = data.member.properties.CountryCode;
          let flag = `<i class="fm-icon 
            ${data.expanded?"fm-expanded-icon":"fm-collapsed-icon"}" 
            title="${data.expanded?"Click to collapse":"Click to expand"}"></i>
            <img class="flag-icon" 
             src="https://cdn.flexmonster.com/i/flags/${name.toLowerCase()}.svg">`;
             cell.text = `${flag}<span style="margin-left: 2px; line-height: 16px">
             ${data.member.caption}</span>`;
          cell.addClass('fm-custom-cell');
        }
      }
    }
    
    <div id="pivot-container"></div>
    
    <div class="demo-box">
      <div class="demo-title"><strong>Overall Cheese Interest by Month</strong></div>
      <div id="amcharts-stacked-container" class="chart-container"></div>
    </div>
    
    <div class="demo-box">
      <div class="demo-title"><strong>Total Cheese Interest by Country</strong></div>
      <div id="amcharts-pictorial-container" class="chart-container"></div>
      <div>Icons made by <a href="https://www.freepik.com" title="Freepik">
    Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">
    www.flaticon.com</a></div>
    </div>
    
    <div class="demo-box">
      <div class="demo-title"><strong>Feta Interest by Month</strong></div>
      <div id="amcharts-pie-container" class="chart-container"></div>
    </div>
    
    <div class="demo-box no-text-before no-text-after">
      <div class="demo-title"><strong>Feta Interest by Country</strong></div>
      <div id="amcharts-map-container" class="chart-container"></div>
    </div>
    
    body {
      font-family: -apple-system, BlinkMacSystemFont, 
    "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", 
    "Segoe UI Emoji", "Segoe UI Symbol";
    }
    
    .chart-container {
      height: 450px;
    }
    
    .demo-box {
      background-color: #fafafa;
      position: relative;
      padding: 40px 30px 30px 30px;
      border: 1px solid #e9e9e9;
      margin-bottom: 20px;
      margin-top: 40px;
    }
    
    .demo-title {
      font-size: 18px;
      margin-bottom: 30px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      line-height: 24px;
    }
    
    .fm-custom-cell {
      display: flex !important;
      align-items: center !important;
      font-size: 12px !important;
    }
    
    .fm-custom-cell .flag-icon {
      width: 21px !important;
      height: 16px !important;
      margin-left: 0 !important;
      margin-right: 2px !important;
    }
    
    #fm-pivot-view .fm-grid-layout .fm-custom-cell.fm-expanded .fm-expanded-icon::before,
    #fm-pivot-view .fm-grid-layout .fm-custom-cell.fm-collapsed .fm-collapsed-icon::before {
      top: -2px;
      height: 16px;
    }
    

    Follow our step-by-step integration with amCharts guide to quickly and easily start creating bright and exciting visualizations.