recharts について
RechartsはD3を基盤とするReact用チャートライブラリです。宣言的で組み合わせ可能な可視化を作る開発者向けに、多様なチャート、レスポンシブ表示、操作性とアクセシビリティを備えています。
主な機能
- 01組み合わせ可能なReactチャートコンポーネント
- 02折れ線、棒、面、円などのチャート
- 03レスポンシブと固定サイズの設定
- 04ツールチップ、ラベル、形状のカスタマイズ
- 05チャート操作と同期
- 06キーボードとスクリーンリーダー対応
活用シーン
- 01Reactの画面にデータチャートを作成
- 02複数のチャート形式を一つの可視化に統合
- 03レスポンシブなダッシュボードを作成
- 04操作可能でアクセシブルなチャートを追加
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ andy-spike/ skills --skill rechartsインストール後、Claude Code で/rechartsを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/api_reference.mdbest_practices.mdexamples.md詳細
Recharts
D3 を基盤とする、合成可能で宣言的なデータ可視化を実現する React 用チャートライブラリです。
クイックスタート
1. Recharts をインストールする
npm install recharts
2. 基本的なチャート構造
Recharts のチャートはすべて、同じパターンに従います。
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
const data = [
{ name: 'Jan', sales: 4000, profit: 2400 },
{ name: 'Feb', sales: 3000, profit: 1398 },
{ name: 'Mar', sales: 2000, profit: 9800 },
];
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="sales" stroke="#8884d8" />
<Line type="monotone" dataKey="profit" stroke="#82ca9d" />
</LineChart>
</ResponsiveContainer>
コアコンセプト
データ形式
Recharts は、オブジェクトの配列としてデータを受け取ります。各オブジェクトはデータポイントを表します。
const data = [
{ month: 'Jan', revenue: 4000, expenses: 2400 },
{ month: 'Feb', revenue: 3000, expenses: 1398 },
];
dataKey プロパティを使用して、オブジェクトのプロパティをチャートコンポーネントに割り当てます。
dataKey="revenue"- revenue プロパティに割り当てますdataKey={(entry) => entry.revenue - entry.expenses}- 計算値に使用する関数です
コンポーネントの組み合わせ
チャートは、専用のコンポーネントを入れ子にして構築します。
サイズ設定:responsive プロパティ(v3.3 以降)、ResponsiveContainer ラッパーを使用するか、width/height を直接設定します
チャートの種類(いずれか 1 つを選択):
LineChart- 折れ線グラフと面グラフBarChart- 棒グラフと縦棒グラフAreaChart- 積み上げ面グラフと塗りつぶし面グラフPieChart- 円グラフとドーナツグラフScatterChart- 散布図とバブルチャートComposedChart- 複合グラフRadarChart- レーダーチャート/スパイダーチャートRadialBarChart- 円形棒グラフ
一般的な子コンポーネント:
XAxis/YAxis- 軸の設定CartesianGrid- グリッド線Tooltip- ホバー時の情報Legend- 系列の識別Line/Bar/Area/Pie- データ系列の表示
種類別のチャートパターン
折れ線グラフ
<LineChart data={data}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="value" stroke="#8884d8" strokeWidth={2} dot={{ r: 4 }} />
</LineChart>
主なプロパティ:
type:"monotone"(滑らか)、"linear"、"step"、"natural"stroke:線の色strokeWidth:線の太さdot:点のスタイル(非表示にするにはfalseに設定)activeDot:ホバー中の点のスタイルconnectNulls:隙間をつなぐにはtrueに設定
面グラフ
<AreaChart data={data}>
<defs>
<linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#8884d8" stopOpacity={0.8}/>
<stop offset="95%" stopColor="#8884d8" stopOpacity={0}/>
</linearGradient>
</defs>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Area type="monotone" dataKey="value" stroke="#8884d8" fillOpacity={1} fill="url(#colorValue)" />
</AreaChart>
積み上げ面グラフ:
<Area type="monotone" dataKey="sales" stackId="1" stroke="#8884d8" fill="#8884d8" />
<Area type="monotone" dataKey="profit" stackId="1" stroke="#82ca9d" fill="#82ca9d" />
棒グラフ
<BarChart data={data}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Bar dataKey="sales" fill="#8884d8" radius={[4, 4, 0, 0]} />
<Bar dataKey="profit" fill="#82ca9d" radius={[4, 4, 0, 0]} />
</BarChart>
主なプロパティ:
fill:棒の色radius:角丸の半径 [左上、右上、右下、左下]。すべての角に同じ値を指定する場合は単一の数値を使用しますbarSize:棒の幅を固定しますstackId:棒をグループ化して積み上げますshape:棒のカスタム形状(関数または要素)
積み上げ棒グラフ:
<Bar dataKey="sales" stackId="a" fill="#8884d8" />
<Bar dataKey="profit" stackId="a" fill="#82ca9d" />
角丸の積み上げ棒グラフ(積み上げ全体を角丸にするには BarStack を使用します):
import { BarStack } from 'recharts';
<BarChart data={data}>
<BarStack stackId="a" radius={[4, 4, 0, 0]}>
<Bar dataKey="sales" fill="#8884d8" />
<Bar dataKey="profit" fill="#82ca9d" />
</BarStack>
</BarChart>
円グラフ
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];
<PieChart>
<Pie
data={data}
dataKey="value"
nameKey="name"
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={80}
paddingAngle={5}
shape={(props) => <Sector {...props} fill={COLORS[props.index % COLORS.length]} />}
/>
<Tooltip />
<Legend />
</PieChart>
主なプロパティ:
innerRadius:0 より大きい値にするとドーナツグラフになりますouterRadius:円グラフのサイズpaddingAngle:スライス間の間隔startAngle/endAngle:部分円グラフ(デフォルト:0 から 360)label:スライス上に値を表示しますshape:各スライスのカスタム描画(非推奨のCellコンポーネントを置き換えます)
散布図
<ScatterChart>
<XAxis type="number" dataKey="x" name="X Axis" />
<YAxis type="number" dataKey="y" name="Y Axis" />
<CartesianGrid />
<Tooltip cursor={{ strokeDasharray: '3 3' }} />
<Scatter name="Series A" data={data} fill="#8884d8" />
</ScatterChart>
複合グラフ
複数の種類のチャートを組み合わせます。
<ComposedChart data={data}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid stroke="#f5f5f5" />
<Tooltip />
<Legend />
<Area type="monotone" dataKey="total" fill="#8884d8" stroke="#8884d8" />
<Bar dataKey="sales" barSize={20} fill="#413ea0" />
<Line type="monotone" dataKey="profit" stroke="#ff7300" />
</ComposedChart>
レスポンシブなサイズ設定
オプション 1:responsive プロパティ(Recharts 3.3 以降、推奨)
チャート自体に responsive を設定します。標準的な CSS のサイズ設定ルールが適用されます。
<LineChart data={data} width="100%" height={300} responsive>
{/* chart components */}
</LineChart>
フレックスボックスや CSS グリッドのレイアウトで使用できます。CSS の style プロパティにも対応しています。
<LineChart data={data} responsive style={{ maxWidth: 800, width: '100%', aspectRatio: '16/9' }}>
{/* chart components */}
</LineChart>
オプション 2:ResponsiveContainer(旧バージョン)
Recharts < 3.3 の場合は、チャートを ResponsiveContainer で囲みます。
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
{/* chart components */}
</LineChart>
</ResponsiveContainer>
重要:ResponsiveContainer の親要素には、サイズが定義されている必要があります。高さにはパーセンテージではなく数値を指定してください。
固定サイズ
width と height をピクセルまたはパーセンテージで直接設定します。
<LineChart data={data} width={600} height={300}>
{/* chart components */}
</LineChart>
軸の設定
XAxis/YAxis のプロパティ
<XAxis
dataKey="name" // property to display
type="category" // "category" or "number"
domain={[0, 'dataMax']} // axis range
tick={{ fill: '#666' }} // tick styling
tickFormatter={(value) => `$${value}`} // format labels
angle={-45} // rotate labels
textAnchor="end" // text alignment
height={60} // extra space for labels
/>
軸の種類
- カテゴリ軸(X 軸のデフォルト):値を離散的なラベルとして扱います
- 数値軸(Y 軸のデフォルト):値を連続的なスケールとして扱います
カスタム範囲
軸の範囲を調整します。
// Fixed range
<YAxis domain={[0, 100]} />
// Auto with padding
<YAxis domain={[0, 'auto']} />
// Data-based with overflow allowed
<YAxis domain={[0, 'dataMax + 100']} allowDataOverflow />
// Logarithmic scale
<YAxis type="number" scale="log" domain={['auto', 'auto']} />
カスタマイズ
カスタムツールチップ
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
return (
<div className="custom-tooltip">
<p className="label">{`${label}`}</p>
<p className="intro">{`Sales: ${payload[0].value}`}</p>
<p className="desc">Additional info...</p>
</div>
);
}
return null;
};
<Tooltip content={<CustomTooltip />} />
カスタム凡例
const CustomLegend = ({ payload }) => (
<ul>
{payload.map((entry, index) => (
<li key={`item-${index}`} style={{ color: entry.color }}>
{entry.value}
</li>
))}
</ul>
);
<Legend content={<CustomLegend />} />
カスタム形状
棒のカスタム形状:
const CustomBar = (props) => {
const { x, y, width, height, fill } = props;
return <path d={`M${x},${y} ...`} fill={fill} />;
};
<Bar shape={<CustomBar />} dataKey="sales" />
// OR
<Bar shape={(props) => <CustomBar {...props} />} dataKey="sales" />
カスタムラベル
<Line
dataKey="sales"
label={{ position: 'top', fill: '#666', fontSize: 12 }}
/>
// Custom label component
<Line
dataKey="sales"
label={<CustomLabel />}
/>
スタイル設定
チャートのスタイル:
<LineChart style={{ backgroundColor: '#f5f5f5' }}>
軸のスタイル:
<XAxis
axisLine={{ stroke: '#666' }}
tickLine={{ stroke: '#666' }}
tick={{ fill: '#666', fontSize: 12 }}
/>
グリッドのスタイル:
<CartesianGrid strokeDasharray="3 3" stroke="#e0e0e0" />
インタラクション
アクティブ要素とインタラクションの制御
Tooltip コンポーネントは、アクティブ要素のハイライトを制御します。activeIndex プロパティは使用しないでください(v3 で削除されました)。
Tooltip のインタラクション用プロパティ:
defaultIndex:レンダリング時に最初にハイライトする項目を設定しますactive:true の場合、インタラクション終了後もツールチップがアクティブなままになりますtrigger:クリックによるインタラクションには"hover"(デフォルト)または"click"を指定しますcontent:カスタムコンテンツ、またはハイライトを維持したままツールチップのテキストを非表示にする() => nullcursor:プロット領域に表示するカーソルです。非表示にするにはfalseを指定します
{/* Click-based interaction with hidden tooltip text */}
<Tooltip trigger="click" content={() => null} cursor={false} />
{/* Default highlighted item on render */}
<Tooltip defaultIndex={2} />
クリックイベント
<LineChart onClick={(e) => console.log(e)}>
<Bar
dataKey="sales"
onClick={(data, index) => console.log('Bar clicked:', data)}
/>
</LineChart>
同期されたチャート
syncId を使って複数のチャートをリンクします:
<LineChart data={data1} syncId="anyId">
{/* components */}
</LineChart>
<LineChart data={data2} syncId="anyId">
{/* components - tooltips synchronize */}
</LineChart>
ズーム用の Brush
<LineChart data={data}>
{/* other components */}
<Brush dataKey="name" height={30} stroke="#8884d8" />
</LineChart>
パフォーマンスの最適化
1. 安定した参照
プロパティには useMemo と useCallback を使用します:
// BAD - new function on every render
<Line dataKey={(entry) => entry.sales * 2} />
// GOOD - stable reference
const dataKey = useCallback((entry) => entry.sales * 2, []);
<Line dataKey={dataKey} />
2. コンポーネントのメモ化
const MemoizedChart = React.memo(({ data }) => (
<LineChart data={data}>
{/* components */}
</LineChart>
));
3. 変更されるコンポーネントの分離
頻繁に更新されるコンポーネントを分離します:
const Chart = () => {
const [hoveredData, setHoveredData] = useState(null);
return (
<LineChart>
{/* Static components */}
<Line dataKey="sales" />
{/* Dynamic overlay */}
<ReferenceLine x={hoveredData?.x} stroke="red" />
</LineChart>
);
};
4. イベントのデバウンス
import { useDebouncedCallback } from 'use-debounce';
const handleMouseMove = useDebouncedCallback((e) => {
setPosition(e.activeLabel);
}, 10);
<LineChart onMouseMove={handleMouseMove}>
5. データポイントの削減
大規模なデータセットでは、集計を検討してください:
// Bin data before rendering
const binnedData = useMemo(() => {
return d3.bin().value(d => d.x)(rawData);
}, [rawData]);
アクセシビリティ
Recharts にはアクセシビリティのサポートが組み込まれています:
<LineChart accessibilityLayer={true}>
<Line dataKey="sales" name="Monthly Sales" />
</LineChart>
アクセシビリティはデフォルトで有効です。チャートはキーボードで操作でき、スクリーンリーダーにも対応しています。
ARIA プロパティ:
<LineChart role="img" aria-label="Sales chart showing monthly revenue">
よく使われるパターン
複数のデータ系列
<LineChart data={data}>
<XAxis dataKey="month" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="productA" name="Product A" stroke="#8884d8" />
<Line type="monotone" dataKey="productB" name="Product B" stroke="#82ca9d" />
<Line type="monotone" dataKey="productC" name="Product C" stroke="#ffc658" />
</LineChart>
横棒グラフ
<BarChart layout="vertical" data={data}>
<XAxis type="number" />
<YAxis type="category" dataKey="name" />
<Bar dataKey="value" />
</BarChart>
ドーナツグラフ
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];
<PieChart>
<Pie
data={data}
innerRadius={60}
outerRadius={80}
paddingAngle={5}
dataKey="value"
shape={(props) => <Sector {...props} fill={COLORS[props.index % COLORS.length]} />}
/>
</PieChart>
注:
Cellコンポーネントは非推奨で、Recharts 4.0 で削除されます。代わりにBar、Pie、Scatterなどのshapeプロパティを使用してください。
参照線/参照領域
<LineChart data={data}>
{/* ... */}
<ReferenceLine y={5000} label="Target" stroke="red" strokeDasharray="3 3" />
<ReferenceArea x1="Jan" x2="Mar" fill="#8884d8" fillOpacity={0.1} />
</LineChart>
エラーバー
<ScatterChart>
<Scatter data={data}>
<ErrorBar dataKey="errorX" width={4} strokeWidth={2} />
<ErrorBar dataKey="errorY" width={4} strokeWidth={2} direction="y" />
</Scatter>
</ScatterChart>
統合パターン
状態管理との連携
const SalesChart = () => {
const [timeRange, setTimeRange] = useState('month');
const data = useSelector(state => selectSalesData(state, timeRange));
return (
<ResponsiveContainer>
<LineChart data={data}>
{/* components */}
</LineChart>
</ResponsiveContainer>
);
};
リアルタイムデータとの連携
const RealtimeChart = () => {
const [data, setData] = useState([]);
useEffect(() => {
const interval = setInterval(() => {
setData(prev => [...prev.slice(-20), newDataPoint]);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<LineChart data={data}>
<XAxis dataKey="time" />
<YAxis domain={['auto', 'auto']} />
<Line type="monotone" dataKey="value" isAnimationActive={false} />
</LineChart>
);
};
Z-index とレイヤー(v3.4 以降)
コンポーネントはデフォルトの順序(グリッド < 軸 < チャート要素 < ツールチップ/凡例)でレンダリングされます。zIndex プロパティで上書きできます:
<Line dataKey="sales" zIndex={10} /> // Render on top
zIndex を直接サポートしていないコンポーネントは、ZIndexLayer でラップします:
import { ZIndexLayer } from 'recharts';
<ZIndexLayer zIndex={5}>
<CustomAnnotation />
</ZIndexLayer>
座標系
Recharts には3つの座標系があります:
- ドメイン座標 - データ値(例:
x="March"、y=5000)。ReferenceLine、ReferenceDot、ReferenceAreaで使用されます。自動的にピクセルに変換されます。 - ピクセル座標 - チャートの viewBox を基準とした位置です。カスタム SVG 図形で使用されます。
usePlotArea()、useOffset()、useChartWidth()フックから取得できます。 - マウスイベント座標 - ブラウザーのビューポートを基準とした座標です。
getRelativeCoordinate(event, element)で変換します。
座標系間の変換:
- データからピクセルへ:
useXAxisScale()、useYAxisScale() - ピクセルからデータへ:
useXAxisInverseScale()、useYAxisInverseScale()
トラブルシューティング
チャートがレンダリングされない
ResponsiveContainerの親要素に寸法が定義されていることを確認します- 高さが数値であることを確認します(ResponsiveContainer ではパーセンテージを指定しないでください)
- データがオブジェクトの配列であることを確認します
ツールチップが表示されない
- Tooltip コンポーネントが含まれていることを確認します
- dataKey の値がデータオブジェクトに存在することを確認します
軸ラベルが重なる
- ラベルを回転します:
<XAxis angle={-45} textAnchor="end" height={80} /> - interval を使用します:
<XAxis interval={0} />(0 = すべて表示、'preserveStartEnd' = 自動)
アニメーションの問題
- 無効にします:
<Line isAnimationActive={false} /> - 再生時間を短くします:
<Line animationDuration={500} />
リソース
参考資料
- API リファレンス - コンポーネントの全プロパティと API の詳細
- 例 - よく使われるチャートパターンとコードスニペット
- ベストプラクティス - パフォーマンスとデザインのガイドライン