En mi código, obtengo una matriz de entradas arrayinput[] y una matriz de números arraynumber[] de mi almacenamiento local. La longitud de las matrices puede variar, pero siempre es arrayinput.length = arraynumber.length .
Ahora quiero crear un gráfico de barras horizontales con estas matrices como datos. Entonces arrayinput está en el eje y y arraynumbers en el eje x. Pero mi problema es que no sé cómo hacerlo, porque las matrices pueden tener cualquier longitud.
¿Es posible agregar las matrices al gráfico de forma dinámica?
Aquí hice un ejemplo de lo que estoy tratando de hacer.
<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 } }] }, } });Puede usar directamente arrayinput dentro de la función, lo mismo para 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 } }] }, } }); Para usar diferentes colores para el gráfico, puede estimar aproximadamente el número máximo de entradas en arrayinput y generar la matriz de colores de ese tamaño. Por ejemplo: si sabe que las entradas en la entrada de arrayinput nunca superarán las 1000, puede crear una matriz de 1000 colores y puede crear una nueva matriz a partir de esto según sus requisitos. Como esto:
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 este colorArray en la función directamente igual que arrayinput . Demostración en vivo aquí: https://codepen.io/Hitesh_Vadher/pen/vYZmdMZ
Sí, es posible, aunque está utilizando una versión muy obsoleta de la biblioteca, es posible que desee considerar actualizarla.
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>