Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

553
Views
React ChartJS: escala el gráfico de barras verticalmente con más conjuntos de datos

Estoy usando React ChartJS para crear un gráfico de barras que actualmente se ve así Gráfico de barras de ReactJS

Los datos sobre los que se construye son dinámicos, es decir, puede haber muchas más industrias (o menos). Me gustaría arreglar el ancho de la barra (digamos, a 30 píxeles) y hacer que el gráfico crezca más alto de acuerdo con la cantidad de conjuntos de datos que tengo. En otras palabras, no me importa qué tan alto sea el gráfico, debería ser una función de cuántos conjuntos de datos tengo.

¿Cómo lograría esto?

Compartiría el código que ya tengo, pero es bastante genérico, puedo publicarlo aquí si la gente lo encuentra útil.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Primero podría envolver el canvas en un div .

 <div id="chartWrapper"> <canvas id="myChart"></canvas> </div>

Puede hacer uso de la API principal del complemento y calcular la altura del gráfico en el beforeRender según el data.barThickness definido y los conjuntos de datasets visibles.

 plugins: [{ beforeRender : chart => { if (!chart.config.options.nonChartAreaHeight) { var yAxis = chart.scales.y; chart.config.options.nonChartAreaHeight = chart.height - (yAxis.bottom - yAxis.top); } const labelCount = chart.data.labels.length; const datasetCount = chart.data.datasets.map((ds, i) => chart.getDatasetMeta(i)).filter(m => !m.hidden).length; const chartAreaHeight = labelCount * datasetCount * chart.data.barThickness * 1.2; document.getElementById("chartWrapper").style.height = (chartAreaHeight + chart.config.options.nonChartAreaHeight) + 'px'; } }],

Luego, también debe definir option.maintainAspectRatio: false para evitar que Chart.js el tamaño del canvas .

Eche un vistazo al código ejecutable a continuación y vea cómo funciona.

 new Chart('myChart', { type: 'bar', plugins: [{ beforeRender : chart => { if (!chart.config.options.nonChartAreaHeight) { var yAxis = chart.scales.y; chart.config.options.nonChartAreaHeight = chart.height - (yAxis.bottom - yAxis.top); } const labelCount = chart.data.labels.length; const datasetCount = chart.data.datasets.map((ds, i) => chart.getDatasetMeta(i)).filter(m => !m.hidden).length; const chartAreaHeight = labelCount * datasetCount * chart.data.barThickness * 1.2; document.getElementById("chartWrapper").style.height = (chartAreaHeight + chart.config.options.nonChartAreaHeight) + 'px'; } }], data: { labels: ['1', '2', '3', '4'], barThickness: 30, // change this to adapt the bar thickness datasets: [{ label: 'Dataset 1', data: [40, 50, 60, 80], backgroundColor: 'red' }, { label: 'Dataset 2', data: [100, 90, 80, 70], backgroundColor: 'blue' }, { label: 'Dataset 3', data: [60, 80, 70, 90], backgroundColor: 'green' }] }, options: { indexAxis: 'y', maintainAspectRatio: false } });
 div { width: 100%; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script> <div id="chartWrapper"> <canvas id="myChart"></canvas> </div>

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!