How to control the width of bar charts in chartjs?

52 Views Asked by At

The bars in my bar chart using chartsjs are too wide. How can i make them thinner? Here is my code

<body>
<div class="chart-container" style="position: relative; height:40vh; width:80vw">
  <canvas id="myChart" ></canvas>
</div> 
<script src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js "></script>
<script>
  const ctx = document.getElementById('myChart');

  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['Males', 'Females'],
      datasets: [{
      label: 'Students Registrations by Gender',
      data: [<?php echo $maleCount; ?>, <?php echo $femaleCount; ?>],
      borderWidth: 1,
      backgroundColor: ['rgb(54, 162, 235)', 'rgb(255, 99, 132)' ]
      }] 
    }
  });
</script>

</body>

I tried many options from chartsjs.org, but none of them fixed my problem.

1

There are 1 best solutions below

1
Ken Lee On BEST ANSWER

For barchart in chartjs , you may specify the barThickness value in the option block, such as

 , options: {
   barThickness:50
 }

So change

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

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>

const ctx = document.getElementById('myChart');
new Chart(ctx, 
  { type: 'bar', 
  data: { labels: ['Males', 'Females'], 
  datasets: 
  [{ label: 'Students Registrations by Gender', 
  data: [100,200 ], 
  borderWidth: 1, 
  backgroundColor: 
  ['rgb(54, 162, 235)', 'rgb(255, 99, 132)' ] }] } 
}
  );
</script>

to

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

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>

const ctx = document.getElementById('myChart');
new Chart(ctx, 
  { type: 'bar', 
  data: { labels: ['Males', 'Females'], 
  datasets: 
  [{ label: 'Students Registrations by Gender', 
  data: [100,200 ], 
  borderWidth: 1, 
  backgroundColor: 
  ['rgb(54, 162, 235)', 'rgb(255, 99, 132)' ] }] } 

 , options: {
   barThickness:50
 }

}
  );

</script>

enter image description here1

will become the following (after specifying barThickness):

enter image description here2