Chart Editor

Update chart while editing grid values

It's fairly easy to use DataGridXL as a chart editor. Listen to the grid's built-in setcellvalues event and update the chart with the latest data.

We're using amCharts for this demo: an excellent chart plugin that offers a free version.

Code

<style>
#grid, #chart {
  height: 300px;
}
</style>

<div id="chart"></div>
<div id="grid"></div>

<script src="https://code.datagridxl.com/datagridxl2.js"></script>
<!-- amCharts (chart plugin) -->
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script>
var my_data = [{
  "country": "USA",
  "visits": 2025,
  "votes": 400
}, {
  "country": "China",
  "visits": 1882,
  "votes": 400
}, {
  "country": "Japan",
  "visits": 1809,
  "votes": 400
}, {
  "country": "Germany",
  "visits": 1422,
  "votes": 400
}, {
  "country": "India",
  "visits": 1522,
  "votes": 500
}, {
  "country": "Netherlands",
  "visits": 1542,
  "votes": 500
}];

var grid;
var chart;

createGrid();
createChart();

function createGrid(){

  grid = new DataGridXL("grid", {
    data: my_data,
    allowDeleteCols: false,
    allowInsertCols: false,
    allowFillCells: true,
    fillCellsDirection: "y",
    expandSheetOnPaste: false,
    allowFreezeCols: false,
    allowFreezeRows: false,
    allowMoveCols: false
  });

  function updateChartData(){

    var gridInstance = this;

    chart.dataProvider = gridInstance.getData();
    chart.validateData();
    chart.animateAgain();

  }

  grid.events.on("setcellvalues", updateChartData);
  grid.events.on("moverows", updateChartData);
  grid.events.on("sort", updateChartData);
  grid.events.on("deleterows", updateChartData);
  grid.events.on("insertrows", updateChartData);

}

function createChart(){

  chart = AmCharts.makeChart( "chart", {
    "type": "serial",
    "theme": "none",
    "dataProvider": my_data,
    "categoryField": "country",
    "startDuration": 1,
    "graphs": [ {
      "balloonText": "[[category]]: [[value]]",
      "fillAlphas": 0.8,
      "lineAlpha": 0.2,
      "type": "column",
      "valueField": "visits",
      "fillColors": "pink",
      "lineColor": "pink"
    }, {
      "balloonText": "[[category]]: [[value]]",
      "fillAlphas": 0.8,
      "lineAlpha": 0.2,
      "type": "column",
      "valueField": "votes",
      "fillColors": "purple",
      "lineColor": "purple"
    } ],
    "chartCursor": {
      "categoryBalloonEnabled": false,
      "cursorAlpha": 0,
      "zoomable": false
    }
  } );

}

</script>

Leave email to receive latest updates!