Jacob York
Jacob York

Reputation: 13

How can I add new data points to an existing chart with chart.js?

I'm using the code below to generate a random graph using chart.js. I'm trying to use a function called nextDay to add new points, but it's not working. nextDay is attached to a button and the goal is every time the button is pressed a new point will be added. Any help would be appreciated.

<script>
            const labels = [
  ];

  const data = {
    labels: labels,
    datasets: [{
      label: 'graph',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: [],
    }]
  };

  const config = {
    type: 'line',
    data: data,
    options: {}
  };
</script>

<script>
function draw(){
const myChart = new Chart(
    document.getElementById('myChart'),
    config
  );
}

        var balance = 0;

        function nextDay(){
                randNum = Math.random() * (max - min) + min;
                data.datasets[0].data.push(randNum);
                labels.push('Week ' + (startingCount + 1));
                myChart.update();
        }

        function sell(){

            balance = balance + randNum;
            console.log("current balance:" + balance);
            randNum = 0;
        }

        function getStartingValues(){
        var max = 100;
        var min = -100;
            for (var startingCount = 0; startingCount < 15; startingCount++)
            {
            var randNum = (Math.random() * (max - min) + min);
            max = randNum + 100;
            min = randNum - 100;
            data.datasets[0].data.push(randNum);
            labels.push('Week ' + (startingCount + 1));
            }
        }
        getStartingValues();
</script>

Upvotes: 1

Views: 1380

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31331

You are updating your original variables, this does not work. You have to update chart.js its internal data like so:

function nextDay() {
  randNum = Math.random() * (max - min) + min;
  myChart.data.datasets[0].data.push(randNum);
  myChart.data.labels.push('Week ' + (startingCount + 1));
  myChart.update();
}

Upvotes: 1

Related Questions