chartschart.jswidth

How to control the width of bar charts in chartjs?


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/chart.js@4.4.2/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.


Solution

  • 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