Update am4charts.XYChart data

Im trying to update the data of my am4charts.XYChart with javascript and i cannt

I have tryed to do again the am4core.create("chartdiv", am4charts.XYChart); but i have a warning doing that.

This is my chart in the HTML code

 <div id="chartdiv"></div>

This is How I initialize the chart

 am4core.ready(function () {

// Themes begin
        am4core.useTheme(am4themes_animated);
// Themes end

        var chart = am4core.create("chartdiv", am4charts.XYChart);

        var data = [];

        for (var i = 0; i < jsonArray.length; i++) {
            var newdate = new Date(jsonArray[i].timestamp);

            data.push({date: newdate, value: jsonArray[i].columna_cierre});
        }

        chart.data = data;

// Create axes
        var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
        dateAxis.renderer.minGridDistance = 60;

        var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

// Create series
        var series = chart.series.push(new am4charts.LineSeries());
        series.dataFields.valueY = "value";
        series.dataFields.dateX = "date";
        series.tooltipText = "{value}"

        series.tooltip.pointerOrientation = "vertical";

        chart.cursor = new am4charts.XYCursor();
        chart.cursor.snapToSeries = series;
        chart.cursor.xAxis = dateAxis;

//chart.scrollbarY = new am4core.Scrollbar();
        chart.scrollbarX = new am4core.Scrollbar();

    });

I want a function to update the values and the axes on the chart. When I do again the he am4core.create("chartdiv", am4charts.XYChart); i have this error Chart was not disposed id-22

Answers:

Answer

am4core.create is for creating the chart, not updating, which is why you're getting an error when calling it again on the same div. The library is telling you to delete the old chart first using the dispose method.

Rather than calling create again, if you want to update the chart data, simply update the chart's data array. If you're replacing the array or adding data to it, the chart will automatically update itself:

chart.data = /* new array */
// or using addData
chart.addData([/* each element you want to add */])

If you're modifying the data in place, call the chart's invalidateData or invalidateRawData method after you make your changes, e.g. chart.invalidateData()

Ideally you'd want to have the chart variable accessible outside of am4core.ready, so creating the variable outside of the function and assigning it inside the ready function is probably your best bet:

var chart;

am4core.ready(function() {
  // ...
  chart = am4core.create(...); //assign to global variable
  // ...
}));

//update chart using global variable

You can find more information on how you can update the chart here.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.