1
0
Fork 0
This repository has been archived on 2023-12-03. You can view files and clone it, but cannot push or open issues or pull requests.
chellaris-galaxy-political-.../components/charts/pops.tsx

97 lines
2.3 KiB
TypeScript

'use client';
import useSWR from "swr";
import { Chart as ChartJS, registerables } from 'chart.js';
import { Pie } from "react-chartjs-2";
import ChartDataLabels, {Context} from 'chartjs-plugin-datalabels';
import { Species } from '../../types/stellaris';
const fetcher = async (url:any) => await fetch(url).then((res) => res.json());
export const PopChart = () => {
const {data: tmpData} = useSWR('/api/species',fetcher);
let data;
if (tmpData) {
let sData: Array<number> = tmpData.speciesArray
data = {
labels: sData.map((_elem, idx) => {
return Species[idx];
}),
datasets: [{
label: 'Portrait Picks',
data: sData,
backgroundColor: [
'rgb(255, 200, 200)',
'rgb(88, 47, 0)',
'rgb(255, 205, 86)',
'rgb(255, 255, 255)',
'rgb(228, 120, 25)',
'rgb(0, 247, 255)',
'rgb(252, 1, 197)',
'rgb(120, 205, 120)',
'rgb(255, 60, 60)',
'rgb(120, 60, 120)',
'rgb(54, 162, 235)',
'rgb(0, 255, 60)',
'rgb(120, 120, 120)'
],
hoverOffset: 4
}]
};
}
else {
data = {
labels: [],
datasets: [{
data: [],
fill: true,
backgroundColor: '#254A6FAA',
borderColor: '#356A9F',
radius: 3
}]
};
}
const config = {
type: 'pie',
data: data,
options: {
plugins: {
tooltip: {
callbacks: {
label: function(ctx: any) {
let sum = 0;
ctx.dataset.data.map((elem: number) => {
sum = sum + Number(elem)
});
return (ctx.dataset.data[ctx.dataIndex]*100/sum).toFixed(1) + "% | " + ctx.dataset.data[ctx.dataIndex] + " / " + sum
}
}
},
legend: {
display: false
},
datalabels: {
formatter: (value: any, context: Context) => {
if (value > 0) {
return Species[context.dataIndex];
}
else {
return "";
}
},
color: 'black'
},
},
},
};
ChartJS.register( ...registerables, ChartDataLabels )
return (
<div className="chart-container h-1/2 aspect-square p-2">
<Pie {...config} />
</div>
);
}