Skip to content

Commit

Permalink
Add Treemap chart for monthly EV maker distribution
Browse files Browse the repository at this point in the history
  • Loading branch information
Ru Chern Chong committed Dec 29, 2023
1 parent 8f47a96 commit 3db5e0f
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
85 changes: 85 additions & 0 deletions app/_components/CarHeatmap.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"use client";

import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { compareAsc, format, parseISO } from "date-fns";
import { API_URL, CHART_COLOURS } from "@/config";
import { Car } from "@/types";

const ApexChart = dynamic(() => import("react-apexcharts"), { ssr: false });

interface CarHeatmapProps {
data: Car[];
}

export const CarHeatmap = ({ data }: CarHeatmapProps) => {
const months: string[] = [...new Set(data.map(({ month }) => month))];
const sortedMonth = months.map((month) => parseISO(month)).sort(compareAsc);
const latestMonth = format(sortedMonth[sortedMonth.length - 1], "yyyy-MM");

const [selectedMonth, setSelectedMonth] = useState(latestMonth);
const [cars, setCars] = useState<Car[]>();

useEffect(() => {
fetch(`${API_URL}/cars/electric?month=${selectedMonth}`)
.then((res) => res.json())
.then((res) => setCars(res));
}, [selectedMonth]);

const options = {
chart: {
toolbar: { show: false },
},
dataLabels: {
enabled: true,
},
colors: CHART_COLOURS,
title: {
text: `Electric Car Make Distribution for ${selectedMonth}`,
align: "center" as "center",
},
};

const series = [
{
data: cars
? cars.map(({ make, number }) => ({
x: make,
y: number,
}))
: [],
},
];

return (
<div className="flex flex-col items-center gap-y-4">
{cars && (
<div className="h-[600px] w-full md:w-[600px]">
<ApexChart
options={options}
series={series}
type="treemap"
width="100%"
height="100%"
/>
</div>
)}
<label htmlFor="months-select">
<select
name="months-select"
id="months-select"
defaultValue={selectedMonth}
onChange={(e) => setSelectedMonth(e.target.value)}
>
{months.map((month) => {
return (
<option key={month} value={month}>
{month}
</option>
);
})}
</select>
</label>
</div>
);
};
2 changes: 2 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from "react";
import { CarHeatmap } from "@/app/_components/CarHeatmap";
import { Infographic } from "@/app/_components/Infographic";
import { API_URL, BASE_URL, EXCLUSION_LIST } from "@/config";
import { sortByMake } from "@/lib/sortByMake";
Expand Down Expand Up @@ -49,6 +50,7 @@ const Home = async () => {
electricCars={filteredElectricCars}
isPopularMake={popularMakes}
/>
<CarHeatmap data={filteredElectricCars} />
</div>
</section>
);
Expand Down

0 comments on commit 3db5e0f

Please sign in to comment.