1

I need to center the pie chart into a component/div and also reduce the size of the chart to fix the cutting out in the ends.

enter image description here

Its cuts-off at bottom and sides.

Code:

export const data = {
  labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
  datasets: [
    {
      label: "# of Votes",
      data: [13,1],
      backgroundColor: [
        "rgba(235, 159, 12,0.7)",
        "rgba(235, 159, 12, 1)",
      ],
      borderColor: [
        "rgba(235, 159, 12, 0.7)",
        "rgba(235, 159, 12, 1)",
      ],
      borderWidth: 1,
      offset:20
    },
  ],
};

export const options = {
    responsive: true,
    maintainAspectRatio: true,
    plugins: {
      title: {
        display: false,
      },
      legend:{
          display:false
      },
    },
  };

function MiniChart() {
  return (
    <div className="flex flex-col w-[150px] lg:w-[200px]">
      <p className="text-center text-md lg:text-lg">Unicorn Startups</p>
      <div className="bg-red-100 w-[150px] h-[150px] lg:w-[200px] lg:h-[200px]">
        <Pie data={data} options={options}/>
      </div>
    </div>
  );
}
Sai Krishnadas
  • 2,863
  • 9
  • 36
  • 69
  • 1
    I made some more tests and find out seems a Chart.js itself bug (when the small pieces of the pie are on the top and the offset is active)... Look again my stackblitz (in particular the dataset `data`) https://stackblitz.com/edit/react-ts-fabpct?file=App.tsx,package.json,index.tsx If you try to switch the data (from my comments) you'll notice that sometime works fine, some other crop the chart (when the big piece is on the bottom). I suggest you to open an issue to the Chart.js repo (https://github.com/chartjs/Chart.js/issues) – Doc Jun 21 '22 at 14:17
  • 1
    https://www.chartjs.org/docs/latest/samples/other-charts/pie.html If you play with the dataset in this live example, you will see that is reproducible also on their own website (`DATA_COUNT=2` and by adding the `offset: 20` in the setup tab for example) – Doc Jun 21 '22 at 14:19
  • Since I use Chart.js in some projects and have not seen any issues regarding this bug, I have opened one myself. Those interested can follow the updates directly on the [Issue](https://github.com/chartjs/Chart.js/issues/10465) on Github – Doc Jul 04 '22 at 15:10
  • 1
    Here's a [workaround](https://github.com/chartjs/Chart.js/issues/10465#issuecomment-1173953554) to the problem (using layout padding option; but you will lose the perfect fit of the chart with the parent container). Thanks to `@stockiNail` on Github. – Doc Jul 04 '22 at 16:05

2 Answers2

0

you can reduce the size of the chart without affecting its ratio by setting the responsive to false. so change
responsive: true to responsive: false

0

This was a bug.

Has been fixed in Chart.Js ^4.0.0.

Here's the solved Issue on Github.

You can check the fix from the website, in the Pie example by acting on the dataset config values, adding some offset.

Doc
  • 655
  • 4
  • 11