Reputation: 15
I'm using the latest version of Chart.js and using Doughnut Chart type. I have doubts on how to find the center of a dataset and rotate to it.
When I click on some datalabel, I need the center of the dataset go to startPosition 0.
I know the Chart.js has a rotation option, but I don’t know how to find the center of the dataset to rotate to it.
Remember that the dataset will be dynamic. So every time I click on each of the datalabels I have to find their center.
Here is my chart code:
const data = {
datasets: [
{
label: 'My First Dataset',
data: [300, 50, 100], // this will be dynamic
backgroundColor: ['rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 205, 86)'],
hoverOffset: 4,
},
],
};
const config = {
type: 'doughnut' as ChartType,
data,
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom' as any,
},
title: {
display: true,
text: 'Chart.js Doughnut Chart',
},
},
},
};
This is what I need:
Here the dataset meta:
How can I do this?
Upvotes: 0
Views: 1728
Reputation: 10572
You need to set up the rotation parameter:
const data = {
datasets: [
{
label: 'My First Dataset',
data: [300, 50, 100],
backgroundColor: ['rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 205, 86)'],
hoverOffset: 4,
rotation: -90,
},
],
};
If you want to have a center of the biggest pie at the top then you need to perform this formula: -(choosenData/2)/(sumOfData)*360
. In your case -300/2/450*360
.
If you want to apply for each pie, then you need to change the order of the data (data element, backougrndColor, etc.) and as the first value set the centered one.
Example for data element 50:
const data = {
datasets: [
{
label: 'My First Dataset',
data: [50, 100, 300],
backgroundColor: ['rgb(54, 162, 235)', 'rgb(255, 205, 86)', 'rgb(255, 99, 132)'],
hoverOffset: 4,
rotation: -25/450*360,
},
],
};
Documentation: Doughnut and Pie Charts, General
Upvotes: 4