Home > Software engineering >  Barchart reducing space between bars
Barchart reducing space between bars

Time:10-19

I am trying to reduce the space between bars, and I am pretty sure it has to be within this piece of code. I removed the code that displays the legend and yAxes assuming I would not need to edit those parts.

A bar chart showing liquid level but with spaces between the data points

barchart = new Chart(myChart, {
                type:'bar',
                data:{
                    labels: {{ data.x_vals | tojson }},
                    datasets:[{
                        label:'Liquid Level',
                        data:{{ data.y_vals }},
                        backgroundColor: gradient,
                        borderWidth:1, //Effects plotted line on chart
                        borderColor:'white',
                        hoverBorderWidth:1,
                        hoverBorderColor:'#000',
                        barPercentage: 1.0,
                        categoryPercentage: 1.0
                    }]
                },
                options:{
                     // legend is here
                    },
                    scales: {
                    // yAxes is here
                xAxes: [{
                    display: true,
                    ticks: {
                        autoSkip: true,
                        padding: 4,
                        fontSize: 12
                    }
                }]
            },

CodePudding user response:

You can set the category and bar percentages to 1:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'blue',
      categoryPercentage: 1,
      barPercentage: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

EDIT:

Make sure you have at least chart.js version 2.9 installed since any version below its not implemented yet

  • Related