angularchart.jsstacked-bar-chart

Define fixed width of bars for Chartjs barchart


I work on an Angular application with charts with Chart.js. On the webpage, I have several charts of type horizontal bar charts.

Here is the definition of the chart in the html template :

<p-chart type="bar" [data]="datas" [plugins]="plugins"
    [options]="options" width="280px" height="60px" />

As you can see, I defined a width for the chart but it corresponds to the width of the canvas, not the width of the bars.

Here is the result :

enter image description here

The width of the bars are different, but with other data it can be the same. I don't have any explanation to this phenomenon. But I would like to fix this issue.

Here are the options of the chart :

{
    indexAxis: 'y',
    animation: false,
    aspectRatio: 0.2,
    maintainAspectRatio: false,
    scales: {
      x: {
        display: false,
      },
      y: {
        display: false,
      },
    },
    x: {
      beginAtZero: true,
      stacked: true,
    },
    y: {
      beginAtZero: true,
      stacked: true,
    },
    cutout: '50%',
    plugins: {
      title: {
        color: 'gray',
        font: {
          weight: 'bold',
          size: 12,
        },
        display: (ctx): boolean => {
          return ctx.chart.data.datasets.some((dataset) => dataset.data.some((value) => value > 0));
        },
        datalabels: {
          color: 'white',
          formatter: (val, ctx): string => {
            if (val) {
              return ctx.chart.data.datasets[ctx.datasetIndex].data[0].toString();
            }
            return '';
          },
        },
        tooltip: {
          enabled: true,
          callbacks: {
            title: (): string => '',
            label: (tooltipItem: any): string => {
              const { chart } = tooltipItem;
              const { label } = chart.data.datasets[tooltipItem.datasetIndex];
              const value: number = chart.data.datasets[tooltipItem.datasetIndex].data[0];
              return `${label}: ${value}`;
            },
          },
        },
      },
      legend: {
        display: false,
        position: 'top',
      },
    },
  }

I tried to change barThickness, barPercentage, categoryPercentage, responsive... Some solutions I found in other topics but nothing worked.

Does anyone have an idea to define a width for the bars so they have the same width, whatever the data are ?

Thanks in advance !


Solution

  • A colleague worked on this issue and he used the percentage values instead of the raw values in the data given to the chart. This fixed the issue !

    Unfortunately, I do not work on the project anymore so I cannot try what kikon and oelimoe suggest in comments.