Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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();
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda