気象データ画面にグラフ追加(Recharts)

- 月別気温折れ線グラフ(最高・平均・最低)
- 月別降水量棒グラフ + 日照時間折れ線グラフ(右軸)
- recharts ^3.7.0 を依存に追加

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Akira
2026-02-28 13:46:08 +09:00
parent 8a1887a26d
commit d11e2a708d
2 changed files with 271 additions and 155 deletions

View File

@@ -15,6 +15,7 @@
"next": "14.1.0", "next": "14.1.0",
"react": "^18", "react": "^18",
"react-dom": "^18", "react-dom": "^18",
"recharts": "^3.7.0",
"tailwind-merge": "^3.4.0" "tailwind-merge": "^3.4.0"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -1,9 +1,13 @@
'use client'; 'use client';
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import {
LineChart, Line, BarChart, Bar, ComposedChart,
XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
} from 'recharts';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import Navbar from '@/components/Navbar'; import Navbar from '@/components/Navbar';
import { Cloud, Loader2, Sun, Droplets, Wind, Thermometer } from 'lucide-react'; import { Cloud, Loader2, Sun, Droplets, Thermometer, Wind } from 'lucide-react';
interface MonthlyRecord { interface MonthlyRecord {
month: number; month: number;
@@ -43,16 +47,34 @@ interface DailyRecord {
pressure_min: number | null; pressure_min: number | null;
} }
const MONTHS = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']; const MONTH_LABELS = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
function fmt(val: number | null, digits = 1): string { function fmt(val: number | null, digits = 1): string {
return val == null ? '—' : val.toFixed(digits); return val == null ? '—' : val.toFixed(digits);
} }
// null を含むグラフデータを安全に変換
function toChartTemp(monthly: MonthlyRecord[]) {
return monthly.map((m) => ({
month: MONTH_LABELS[m.month - 1],
平均: m.temp_mean_avg,
最高: m.temp_max_avg,
最低: m.temp_min_avg,
}));
}
function toChartPrecipSunshine(monthly: MonthlyRecord[]) {
return monthly.map((m) => ({
month: MONTH_LABELS[m.month - 1],
降水量: m.precip_total != null ? Math.round(m.precip_total) : null,
日照時間: m.sunshine_total != null ? Math.round(m.sunshine_total) : null,
}));
}
export default function WeatherPage() { export default function WeatherPage() {
const currentYear = new Date().getFullYear(); const currentYear = new Date().getFullYear();
const [year, setYear] = useState(currentYear); const [year, setYear] = useState(currentYear);
const [tab, setTab] = useState<'summary' | 'recent'>('summary'); const [tab, setTab] = useState<'chart' | 'summary' | 'recent'>('chart');
const [summary, setSummary] = useState<SummaryResponse | null>(null); const [summary, setSummary] = useState<SummaryResponse | null>(null);
const [summaryLoading, setSummaryLoading] = useState(true); const [summaryLoading, setSummaryLoading] = useState(true);
@@ -74,12 +96,9 @@ export default function WeatherPage() {
end.setDate(end.getDate() - 1); end.setDate(end.getDate() - 1);
const start = new Date(end); const start = new Date(end);
start.setDate(start.getDate() - 13); start.setDate(start.getDate() - 13);
const fmt2 = (d: Date) => d.toISOString().slice(0, 10); const fmtDate = (d: Date) => d.toISOString().slice(0, 10);
api.get(`/weather/records/?start=${fmt2(start)}&end=${fmt2(end)}`) api.get(`/weather/records/?start=${fmtDate(start)}&end=${fmtDate(end)}`)
.then((res) => { .then((res) => setRecentRecords([...res.data].reverse()))
const data: DailyRecord[] = res.data;
setRecentRecords([...data].reverse());
})
.catch((err) => console.error(err)) .catch((err) => console.error(err))
.finally(() => setRecentLoading(false)); .finally(() => setRecentLoading(false));
}, []); }, []);
@@ -87,6 +106,9 @@ export default function WeatherPage() {
const years: number[] = []; const years: number[] = [];
for (let y = currentYear; y >= 2016; y--) years.push(y); for (let y = currentYear; y >= 2016; y--) years.push(y);
const tempData = summary ? toChartTemp(summary.monthly) : [];
const precipData = summary ? toChartPrecipSunshine(summary.monthly) : [];
return ( return (
<div className="min-h-screen bg-gray-50"> <div className="min-h-screen bg-gray-50">
<Navbar /> <Navbar />
@@ -98,7 +120,6 @@ export default function WeatherPage() {
<Cloud className="h-6 w-6 text-sky-500" /> <Cloud className="h-6 w-6 text-sky-500" />
<h1 className="text-2xl font-bold text-gray-900"></h1> <h1 className="text-2xl font-bold text-gray-900"></h1>
</div> </div>
<div className="flex items-center gap-3">
<select <select
value={year} value={year}
onChange={(e) => setYear(Number(e.target.value))} onChange={(e) => setYear(Number(e.target.value))}
@@ -109,42 +130,10 @@ export default function WeatherPage() {
))} ))}
</select> </select>
</div> </div>
</div>
{/* タブ */} {/* 年間サマリーカード(常に表示) */}
<div className="flex border-b border-gray-200 mb-6"> {!summaryLoading && summary && (
<button <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
onClick={() => setTab('summary')}
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
tab === 'summary'
? 'border-sky-500 text-sky-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}
>
</button>
<button
onClick={() => setTab('recent')}
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
tab === 'recent'
? 'border-sky-500 text-sky-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}
>
14
</button>
</div>
{/* ===== 月別サマリー ===== */}
{tab === 'summary' && (
summaryLoading ? (
<div className="flex justify-center py-20">
<Loader2 className="h-6 w-6 animate-spin text-gray-400" />
</div>
) : summary ? (
<div className="space-y-4">
{/* 年間サマリーカード */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
<div className="bg-white rounded-lg shadow p-4"> <div className="bg-white rounded-lg shadow p-4">
<div className="flex items-center gap-1.5 mb-1"> <div className="flex items-center gap-1.5 mb-1">
<Thermometer className="h-4 w-4 text-orange-400" /> <Thermometer className="h-4 w-4 text-orange-400" />
@@ -184,8 +173,137 @@ export default function WeatherPage() {
</p> </p>
</div> </div>
</div> </div>
)}
{/* 月別テーブル */} {/* タブ */}
<div className="flex border-b border-gray-200 mb-6">
{(['chart', 'summary', 'recent'] as const).map((t) => (
<button
key={t}
onClick={() => setTab(t)}
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
tab === t
? 'border-sky-500 text-sky-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}
>
{t === 'chart' ? 'グラフ' : t === 'summary' ? '月別サマリー' : '直近14日'}
</button>
))}
</div>
{/* ===== グラフタブ ===== */}
{tab === 'chart' && (
summaryLoading ? (
<div className="flex justify-center py-20">
<Loader2 className="h-6 w-6 animate-spin text-gray-400" />
</div>
) : summary ? (
<div className="space-y-6">
{/* 気温グラフ */}
<div className="bg-white rounded-lg shadow p-5">
<h3 className="text-sm font-semibold text-gray-700 mb-4"></h3>
<ResponsiveContainer width="100%" height={280}>
<LineChart data={tempData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
<XAxis dataKey="month" tick={{ fontSize: 12 }} />
<YAxis
tick={{ fontSize: 12 }}
tickFormatter={(v) => `${v}`}
domain={['auto', 'auto']}
/>
<Tooltip
formatter={(value: number | null) => value == null ? '—' : `${value.toFixed(1)}`}
/>
<Legend />
<Line
type="monotone"
dataKey="最高"
stroke="#f97316"
strokeWidth={2}
dot={{ r: 3 }}
connectNulls
/>
<Line
type="monotone"
dataKey="平均"
stroke="#22c55e"
strokeWidth={2.5}
dot={{ r: 3 }}
connectNulls
/>
<Line
type="monotone"
dataKey="最低"
stroke="#3b82f6"
strokeWidth={2}
dot={{ r: 3 }}
connectNulls
/>
</LineChart>
</ResponsiveContainer>
</div>
{/* 降水量・日照時間グラフ */}
<div className="bg-white rounded-lg shadow p-5">
<h3 className="text-sm font-semibold text-gray-700 mb-4">mmh</h3>
<ResponsiveContainer width="100%" height={280}>
<ComposedChart data={precipData} margin={{ top: 5, right: 40, left: 0, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
<XAxis dataKey="month" tick={{ fontSize: 12 }} />
<YAxis
yAxisId="precip"
orientation="left"
tick={{ fontSize: 12 }}
tickFormatter={(v) => `${v}`}
label={{ value: 'mm', position: 'insideTopLeft', offset: 5, fontSize: 11, fill: '#6b7280' }}
/>
<YAxis
yAxisId="sunshine"
orientation="right"
tick={{ fontSize: 12 }}
tickFormatter={(v) => `${v}h`}
/>
<Tooltip
formatter={(value: number | null, name: string) => {
if (value == null) return '—';
return name === '降水量' ? `${value} mm` : `${value} h`;
}}
/>
<Legend />
<Bar
yAxisId="precip"
dataKey="降水量"
fill="#93c5fd"
radius={[3, 3, 0, 0]}
/>
<Line
yAxisId="sunshine"
type="monotone"
dataKey="日照時間"
stroke="#fbbf24"
strokeWidth={2.5}
dot={{ r: 3 }}
connectNulls
/>
</ComposedChart>
</ResponsiveContainer>
</div>
</div>
) : (
<div className="py-20 text-center text-gray-500 text-sm"></div>
)
)}
{/* ===== 月別サマリー ===== */}
{tab === 'summary' && (
summaryLoading ? (
<div className="flex justify-center py-20">
<Loader2 className="h-6 w-6 animate-spin text-gray-400" />
</div>
) : summary ? (
<div className="bg-white rounded-lg shadow overflow-hidden"> <div className="bg-white rounded-lg shadow overflow-hidden">
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="w-full text-sm"> <table className="w-full text-sm">
@@ -205,7 +323,7 @@ export default function WeatherPage() {
<tbody className="divide-y divide-gray-100"> <tbody className="divide-y divide-gray-100">
{summary.monthly.map((m) => ( {summary.monthly.map((m) => (
<tr key={m.month} className="hover:bg-gray-50"> <tr key={m.month} className="hover:bg-gray-50">
<td className="px-3 py-2 font-medium text-gray-900">{MONTHS[m.month - 1]}</td> <td className="px-3 py-2 font-medium text-gray-900">{MONTH_LABELS[m.month - 1]}</td>
<td className="px-3 py-2 text-right text-gray-700"> <td className="px-3 py-2 text-right text-gray-700">
{m.temp_mean_avg == null ? '—' : ( {m.temp_mean_avg == null ? '—' : (
<span className={m.temp_mean_avg >= 25 ? 'text-orange-500 font-medium' : m.temp_mean_avg < 5 ? 'text-blue-500 font-medium' : ''}> <span className={m.temp_mean_avg >= 25 ? 'text-orange-500 font-medium' : m.temp_mean_avg < 5 ? 'text-blue-500 font-medium' : ''}>
@@ -233,7 +351,6 @@ export default function WeatherPage() {
猛暑日: 最高気温 35 冬日: 最低気温 &lt; 0 雨天日: 降水量 1mm 猛暑日: 最高気温 35 冬日: 最低気温 &lt; 0 雨天日: 降水量 1mm
</div> </div>
</div> </div>
</div>
) : ( ) : (
<div className="py-20 text-center text-gray-500 text-sm"></div> <div className="py-20 text-center text-gray-500 text-sm"></div>
) )
@@ -266,8 +383,7 @@ export default function WeatherPage() {
<tr> <tr>
<td colSpan={8} className="px-3 py-8 text-center text-gray-400"></td> <td colSpan={8} className="px-3 py-8 text-center text-gray-400"></td>
</tr> </tr>
) : ( ) : recentRecords.map((r) => (
recentRecords.map((r) => (
<tr key={r.date} className="hover:bg-gray-50"> <tr key={r.date} className="hover:bg-gray-50">
<td className="px-3 py-2 font-medium text-gray-900 whitespace-nowrap">{r.date}</td> <td className="px-3 py-2 font-medium text-gray-900 whitespace-nowrap">{r.date}</td>
<td className="px-3 py-2 text-right text-gray-700">{fmt(r.temp_mean)}</td> <td className="px-3 py-2 text-right text-gray-700">{fmt(r.temp_mean)}</td>
@@ -290,8 +406,7 @@ export default function WeatherPage() {
<td className="px-3 py-2 text-right text-gray-500">{fmt(r.wind_max)}</td> <td className="px-3 py-2 text-right text-gray-500">{fmt(r.wind_max)}</td>
<td className="px-3 py-2 text-right text-gray-500">{fmt(r.pressure_min, 0)}</td> <td className="px-3 py-2 text-right text-gray-500">{fmt(r.pressure_min, 0)}</td>
</tr> </tr>
)) ))}
)}
</tbody> </tbody>
</table> </table>
</div> </div>