Add Species Pie Chart
This commit is contained in:
parent
ac7fb85535
commit
e80a54eb71
4 changed files with 205 additions and 1 deletions
components/charts
100
components/charts/pops.tsx
Normal file
100
components/charts/pops.tsx
Normal file
|
@ -0,0 +1,100 @@
|
|||
'use client';
|
||||
|
||||
import useSWR from "swr";
|
||||
import { Chart as ChartJS, registerables } from 'chart.js';
|
||||
import { Pie } from "react-chartjs-2";
|
||||
import ChartDataLabels 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: true
|
||||
},
|
||||
datalabels: {
|
||||
formatter: (value: any, context: any) => {
|
||||
if (value > 0) {
|
||||
return Species[context.dataIndex];
|
||||
}
|
||||
else {
|
||||
return "";
|
||||
}
|
||||
},
|
||||
anchor: 'center',
|
||||
align: 'end',
|
||||
color: 'black'
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
ChartJS.register( ...registerables, ChartDataLabels )
|
||||
|
||||
return (
|
||||
<div className="chart-container h-1/2 aspect-square p-2">
|
||||
<Pie {...config} />
|
||||
</div>
|
||||
);
|
||||
}
|
Reference in a new issue