Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
Add data dynamically to chart

In my code I'm getting an array of inputs arrayinput[] and an array of numbers arraynumber[] from my local storage. The length of the arrays can vary, but it's always arrayinput.length = arraynumber.length.

Now I want to create a horizontal bar chart with these arrays as data. So arrayinput is on the y axis and arraynumbers on the x axis. But my problem is I don't know how to do that, because the arrays can have any length.

Is it possible to add the arrays to the chart dynamically?

Here I made an example of what I'm trying to do.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
    <div class="chartcontainer">
<canvas id="bar-chart-horizontal" ></canvas>
   </div>
let arrayinput = ["apple", "banana", "pineapple", "cherry","peach"] ;
let arraynumber = ["5", "10", "3", "8", "1"];

var number=[];
for(var i=0;i<arrayinput.length;i++){
     number[i] = parseInt(arraynumber[i]);
}

new Chart(document.getElementById("bar-chart-horizontal"), {
    type: 'horizontalBar',
    data: {
     
//here I want all elements of arrayinut
      labels: ["apple", "banana", "pineapple", "cherry","peach"],
      datasets: [
        {
          label: "Number of fruits",
//here I need to create arrayinput.length differnt colors but thats not that important now           
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],

  //here I want the elements of number
          data: [5,10,3,8,1]
        }
      ]
    },
    options: {
      legend: { display: false },
      title: {
        display: true,
        text: 'Fruits'
      },
        scales: {
           xAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
        },
     
    }
});
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can directly use arrayinput inside the function, same for arraynumber.

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<div class="chartcontainer">
    <canvas id="bar-chart-horizontal"></canvas>
</div>

Javascript:

var arrayinput = ["apple", "banana", "pineapple", "cherry","peach"] ;
var arraynumber = ["5", "10", "3", "8", "1"];

var number=[];
for(var i=0;i<arrayinput.length;i++){
     number[i] = parseInt(arraynumber[i]);
}

new Chart(document.getElementById("bar-chart-horizontal"), {
    type: 'horizontalBar',
    data: {
     
//here I want all elements of arrayinut
      labels: arrayinput,
      datasets: [
        {
          label: "Number of fruits",
//here I need to create arrayinput.length differnt colors but thats not that important now           
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],

  //here I want the elements of number
          data: arraynumber
        }
      ]
    },
    options: {
      legend: { display: false },
      title: {
        display: true,
        text: 'Fruits'
      },
        scales: {
           xAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
        },
     
    }
});

For using different colors for the chart, you can roughly estimate the maximum number of entries in arrayinput and generate the color array of that size. For example: If you know that entries in the arrayinput will never exceed 1000, you can make an array of 1000 colors, and can make a new array of out of this as per your requirement. Like this:

var backgroundColor = ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"];
var colorArray = [];

//Max value of arrayinput is say 5

for(var i=0; i<arrayinput.length; i++) {
    colorArray.push(backgroundColor[i]);
}

Use this colorArray in the function directly same like arrayinput. Live Demo Here: https://codepen.io/Hitesh_Vadher/pen/vYZmdMZ

about 4 years ago · Juan Pablo Isaza Denunciar

0

Yes it is possible, although you are using a verry outdated version of the lib you might want to consider updating it

V2:

const chart = new Chart(document.getElementById("bar-chart-horizontal"), {
  type: 'horizontalBar',
  data: {

    //here I want all elements of arrayinut
    labels: [],
    datasets: [{
      label: "Number of fruits",
      //here I need to create arrayinput.length differnt colors but thats not that important now           
      backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850"],

      //here I want the elements of number
      data: []
    }]
  },
  options: {
    legend: {
      display: false
    },
    title: {
      display: true,
      text: 'Fruits'
    },
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },

  }
});

const addFruits = () => {
  chart.data.labels = ["apple", "banana", "pineapple", "cherry", "peach"];
  chart.data.datasets[0].data =  [5, 10, 3, 8, 1];
  chart.update();
}

addFruits()
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<div class="chartcontainer">
  <canvas id="bar-chart-horizontal"></canvas>
</div>

V3:

const chart = new Chart(document.getElementById("bar-chart-horizontal"), {
  type: 'bar',
  data: {

    //here I want all elements of arrayinut
    labels: [],
    datasets: [{
      label: "Number of fruits",
      //here I need to create arrayinput.length differnt colors but thats not that important now           
      backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850"],

      //here I want the elements of number
      data: []
    }]
  },
  options: {
    indexAxis: 'y',
    plugins: {
      legend: {
        display: false
      },
      title: {
        display: true,
        text: 'Fruits'
      },
    },
    scales: {
      y: {
        beginAtZero: false
      }
    },

  }
});

const addFruits = () => {
  chart.data.labels = ["apple", "banana", "pineapple", "cherry", "peach"];
  chart.data.datasets[0].data = [5, 10, 3, 8, 1];
  chart.update();
}

addFruits()
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.min.js"></script>
<div class="chartcontainer">
  <canvas id="bar-chart-horizontal"></canvas>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda