Chartjs-Updating data in chart.js

2👍

If you need to access the chart variable, make the scope more accessible.

Initialize it as null at the top and assign it in the function. You can then access it later.

const colores = ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850"];
const etiquetas = ["Africa", "Asia", "Europe", "Latin America", "North America"];

var myPieChart = null; // "global" access...

function pieChart(datos) {
  let ctx = document.getElementById("pie-chart").getContext("2d");
  let tipo = 'pie';
  let titulo = 'Predicted world population (millions) in 2050';

  myPieChart = new Chart(ctx, {
    type: tipo,
    data: {
      labels: etiquetas,
      datasets: [{
        label: "Population (millions)",
        backgroundColor: colores,
        borderWidth: 1,
        borderColor: '#FFF',
        data: datos,
      }]
    },
    options: {
      title: {
        display: true,
        text: titulo
      }
    }
  });
}

function addData(chart, title, data) {
  chart.options.title.text = title;
  chart.data.datasets.forEach((dataset, i) => {
    dataset.data = data;
  });
  chart.update();
}

function removeData(chart) {
  chart.data.datasets.forEach((dataset) => {
    dataset.data.pop();
  });
  chart.update();
}

// MAIN
$(document).ready(function() {
  pieChart([2478, 5267, 734, 784, 433]);

  // Botón pulsado
  $('.btn_graf').click(function() {
    let id_btn = $(this).attr("id");

    if (id_btn == 'bat_graf_btn') {
      removeData(myPieChart);
      addData(myPieChart, "Population (millions)", [2, 5, 7, 7, 4]);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css" rel="stylesheet" />
<canvas id="pie-chart"></canvas>
<button class="btn_graf" id="bat_graf_btn">Change Data</button>

Leave a comment