I would like to know if there is a way to make the chart’s width increase if the number of items in the legend doesn’t fit with its initial size
I tried a lot of different settings and approces like changing style attributes on container but none of them could solve my problem.
I use Chart.js v3.8.1
I prepared a codepen to help me explain the request:
Codepen
<div class="container">
<div class="chart-container">
<canvas style="height: 300px; width: 100%"></canvas>
</div>
</div>
.container {
width: 100%;
height: 400px;
border: 3px solid red;
display: flex;
}
.chart-container {
border: 2px solid blue;
width: fit-content;
margin: auto 0;
width: fit-content;
}
canvas {
border: 2px solid green;
}
$(document).ready(() => {
let preparedData = prepareData(60);
const config = {
type: "doughnut",
data: preparedData,
options: {
responsive: false,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
position: "right"
}
}
}
};
let chart = new Chart($("canvas"), config);
});
function prepareData(numData) {
let labels = [];
let localData = [];
for (idx = 0; idx < numData; idx++) {
labels.push("Data " + idx);
let random = getRandomInt(100);
localData.push(random);
}
let datasets = [
{
label: "Info",
data: localData,
borderWidth: 0
}
];
return { labels, datasets };
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
2
Answers
You can adjust the width dynamically by following these steps:
If i understand correctly, you want to show all legend labels in the chart, right?.
You can set more height to the canvas, so all legend items can fit in the size of the chart, because in pie and donut charts the aspect ratio by default is 1. (try for example height 500px instead of 300px in the canvas element). You can do a function that calculates the best height based on the number of items.
Maybe you can change also the "aspectRatio" in the options of the chart and you will get the same result, but not totally sure about this solution.