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
Raw Normal View History

2023-06-01 23:06:04 +00:00
'use client';
import useSWR from "swr";
import { Chart as ChartJS, registerables } from 'chart.js';
import { Pie } from "react-chartjs-2";
2023-06-01 23:41:58 +00:00
import ChartDataLabels, {Context} from 'chartjs-plugin-datalabels';
2023-06-01 23:06:04 +00:00
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/v1/species',fetcher);
2023-06-01 23:06:04 +00:00
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',
2023-06-01 23:06:04 +00:00
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: {
2023-06-01 23:41:58 +00:00
display: false
2023-06-01 23:06:04 +00:00
},
datalabels: {
2023-06-01 23:22:41 +00:00
formatter: (value: any, context: Context) => {
2023-06-01 23:06:04 +00:00
if (value > 0) {
return Species[context.dataIndex];
}
else {
return "";
}
},
color: 'black'
},
},
},
};
ChartJS.register( ...registerables, ChartDataLabels )
return (
<div className='chart-container'>
<Pie className='chart' {...config} />
2023-06-01 23:06:04 +00:00
</div>
);
}