Jeroen
Jeroen

Reputation: 2093

ChartJS: Fixed width for data-part, the rest for labels

I'm using ChartJS to display multiple charts on a page. Each chart has a different dataset, and different labels (some have short labels, some have long labels).

Currently the width of the actual 'data-part' (the part of the chart showing e.g. Bars) depends on how much space the labels take. I would like to make all charts have a fixed size for the data-part, and let the labels take up the remaining size.

See for example the following screenshot. Here I display 2 charts, but the actual data-part is different for both, because one has shorter labels than the other. enter image description here

What I would like is to set for example a fixed width of 400px for the data-part, and let the labels take the remaining space left on the page. That way the charts would be aligned perfectly above each other.

Even better would be if I could set that for each chart the data-part takes a percentage of the width (e.g. 70%), so the labels take the rest (30%).

I have checked the ChartJS documentation, but the only I can find it setting the width for the entire chart-component.

Upvotes: 2

Views: 1620

Answers (2)

rocketsarefast
rocketsarefast

Reputation: 4170

One option is to set a large fixed width for the y axis scale on all the charts.

o.options.scales.y.afterFit = function(axis) {axis.width = 150;};

This is done by attaching a callback to the afterFit event of the y axis and just overriding the calculated width with a big fixed number.

Before:

enter image description here

After:

enter image description here

Upvotes: 4

Jatin__c
Jatin__c

Reputation: 21

Cheeky solution - you can add a dummy chart before your charts having the same labels.
Let's call this dummy chart as chart D and your main chart as chart M. In M, you would fix it's width and hide the labels by writing in options -

scales: {y: {ticks: {display: false}}}

Now you have a fixed data width.
In D, you would just display the labels and hide the data part (hiding grid lines, legend, title, etc.).
So now you have two charts side-by-side, one is displaying just the labels and the other displaying the bars, just need to position it in such a way that no matter how long the label is, it does not overlap with M.

Repeat the step similarly for all charts and have the same width for M1,M2,M3,...
This is a solution that seemed to work for me.

Upvotes: 2

Related Questions