Leff
Leff

Reputation: 1370

Chart js - set width to a specific bar

I am using chart.js and it's bar chart. I am displaying some data for the period of 12 months. What I would like to do is to set the width of the bar that is representing current month to a higher value than the others. But, I am not sure how to do this, since I only saw an option of setting the width to every bar in the dataset. This are my options that I currently have:

const options = {
    type: "bar",
    data: {
        labels: counties.map(county => dateStringEU(county.Date.split(" ")[0])).reverse(),
        datasets: [
            {
                backgroundColor: "#006BE8",
                borderColor: "rgba(151,187,205,1)",
                barPercentage: 0.9,
                categoryPercentage: 0.9,
            }
        ]
    },
    options: {
        legend: {
            display: false
        },
        scales: {
            yAxes: [
                {
                    ticks: {
                        fontColor: '#736B8A',
                        beginAtZero: true,
                        stepSize: 100
                    },
                    gridLines: {
                        display: false
                    }
                }
            ],
            xAxes: [
                {
                    ticks: {
                        fontColor: '#736B8A'
                    },
                    gridLines: {
                        display: false
                    }
                }
            ]
        }
    }
}

Is it possible to set the width individually for each bar and how can we do it if so?

Upvotes: 0

Views: 381

Answers (1)

uminder
uminder

Reputation: 26190

Despite it's not clearly documented, you can define barPercentage as an array of values.

barPercentage: [0.5, 0.5, 0.5, 0.5, 1, 0.5, 0.5],

Please have a look at the amended code from Chart.js bar documentation.

new Chart(document.getElementById("chart"), {
  type: "bar",
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First Dataset",
      data: [65, 59, 80, 81, 56, 55, 40],
      barPercentage: [0.5,0.5,0.5,0.5,1,0.5,0.5],
      categoryPercentage: 1,
      fill: false,
      backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
      borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="80"></canvas>

Upvotes: 1

Related Questions