はじめに
セットアップと最初のチャート
Chart.js は canvas 要素に描画します。type プロパティでチャートタイプを設定し、data にラベルと、値とスタイリングを持つ datasets を入れます。
<!-- include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: 'Votes',
data: [12, 19, 3],
backgroundColor: ['red', 'blue', 'green']
}]
}
});
</script>npm インストールと ES モジュールのインポート
最も簡単なセットアップには 'chart.js/auto' を使います — Chart.js とすべてのコントローラー/要素をインポートして自動登録してくれます。本番のバンドルサイズを小さくしたい場合は tree-shaking を選びましょう:'chart.js' からインポートし、使う部品だけを登録します。
# install
npm install chart.js
// import the auto-bundled build (registers everything)
import Chart from 'chart.js/auto';
const ctx = document.getElementById('myChart');
const chart = new Chart(ctx, {
type: 'line',
data: { /* ... */ },
options: { responsive: true }
});Canvas と 2D コンテキスト
Chart.js は <canvas> 要素でもその 2d レンダリングコンテキス トでも受け付けます。responsive が true のとき canvas はコンテナいっぱいにリサイズされるため、width/height の HTML 属性はフォールバックにすぎません。1 つの canvas が保持できる Chart インスタンスは正確に 1 つです。
// Chart.js accepts a canvas element OR a 2D context
const canvas = document.getElementById('myChart');
const chart = new Chart(canvas, { type: 'bar', data: {...} });
// equivalent: pass the 2d context
const ctx = canvas.getContext('2d');
const chart2 = new Chart(ctx, { type: 'bar', data: {...} });
// one chart per canvas; the canvas size is controlled by
// responsive options, NOT the width/height attributes利用可能なチャートタイプ
Chart.js には 8 つのチャートタイプが付属します。bar、line、scatter、bubble は直交軸を、pie、doughnut、polarArea は円形を、radar は独自の放射軸を使います。トップレベルの 'type' フィールドで全 dataset に使うコントローラーを選択します(dataset が独自の type で上書きしない限り)。
// the 8 built-in chart types
const types = ['bar', 'line', 'pie', 'doughnut',
'radar', 'polarArea', 'bubble', 'scatter'];
// each type maps to a controller:
// bar/line -> Cartesian controllers
// pie/doughnut/polarArea -> circular controllers
// radar -> radar controller
// bubble/scatter -> cartesian with point parsing
new Chart(ctx, { type: 'polarArea', data: {...} });Tree-Shaking と登録
'chart.js'(/auto ではない)からインポートした場合は何も登録されないため、コントローラー、要素、スケール、プラグインを自分で登録する必要があります。この tree-shakeable なアプローチはバンドルサイズを大幅に削減できます。コンポーネントの登録忘れは「scale is not a registered scale」エラーの最も一般的な原因です。
import {
Chart,
BarController,
BarElement,
CategoryScale,
LinearScale,
Legend,
Title,
Tooltip,
} from 'chart.js';
// register ONLY what you use -> smaller bundle
Chart.register(
BarController, BarElement,
CategoryScale, LinearScale,
Legend, Title, Tooltip,
);
new Chart(ctx, {
type: 'bar',
data: { labels: ['A', 'B'], datasets: [{ data: [1, 2] }] },
});破棄とライフサイクル
各 Chart インスタンスは自分の canvas と付加したイベントリスナーを所有します。destroy() を呼ぶとすべてが取り壊され、canvas を再利用できるようになります — SPA や React/Vue の effect では不可欠です。稼働中の canvas に 2 つ目のチャートを作るとメモリリークし、グラフィックが二重描画されます。
const chart = new Chart(ctx, config);
// ...later, to re-render with new config:
chart.destroy(); // cleans up listeners and canvas
const fresh = new Chart(ctx, newConfig);
// never create two Chart instances on the same canvas;
// always destroy() the old one first.棒グラフ
基本の棒グラフ
棒グラフは各ラベルを、高さがデータ値に等しいバーへ対応させます。backgroundColor がバーの塗りを、borderColor/borderWidth が輪郭を設定します。y.beginAtZero を設定してバーが必ずゼロから始まるようにしましょう — なければ Chart.js が軸の最小値を自動スケールし、差が視覚的に歪みます。
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'Revenue',
data: [12, 19, 7, 15, 22],
backgroundColor: 'rgba(54, 162, 235, 0.6)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: { scales: { y: { beginAtZero: true } } }
});横棒グラフ(indexAxis)
Chart.js v3 以降、横棒は 'bar' タイプに indexAxis: 'y' を付けて作ります — 旧 'horizontalBar' タイプは削除されました。x スケールが値軸になります。横棒は、縦グラフでは重なり合う長いカテゴリラベルに最適です。
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Task A', 'Task B', 'Task C'],
datasets: [{ label: 'Hours', data: [5, 8, 3] }]
},
options: {
indexAxis: 'y', // horizontal bars (v3+ syntax)
scales: { x: { beginAtZero: true } }
}
});グループ化されたバー(複数 dataset)
棒グラフの複数 dataset はデフォルトで並んで(グループ化して)配置されます。Chart.js は backgroundColor を省略したときだけ色を自動割り当てるため、予測可能 な出力のために dataset ごとに明示的な色を設定しましょう。各 dataset は x 軸で同じ labels 配列を共有します。
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Q1', 'Q2', 'Q3', 'Q4'],
datasets: [
{ label: '2023', data: [20, 35, 30, 35],
backgroundColor: 'rgba(255,99,132,0.6)' },
{ label: '2024', data: [25, 32, 34, 40],
backgroundColor: 'rgba(54,162,235,0.6)' }
]
},
options: { scales: { y: { beginAtZero: true } } }
});積み上げバー
積み上げバーには x と y の両方のスケールに stacked: true が必要です。各 dataset のバーは前のバーの上に描かれ、合計になります。積み上げは構成を示せますが、グループ化されたバーに比べ、上の系列のカテゴリ間比較は難しくなります。
new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [
{ label: 'Men', data: [20, 35, 30], backgroundColor: '#36A2EB' },
{ label: 'Women', data: [25, 32, 34], backgroundColor: '#FF6384' }
]
},
options: {
scales: {
x: { stacked: true },
y: { stacked: true, beginAtZero: true }
}
}
});バーのスタイリング
borderRadius はバーの角を丸めます(単一の数値は全角に適用、{topLeft:8} のようなオブジェクトは特定の角を対象)。borderSkipped はデフォルト 'start' で 1 辺を描かず — false にすると 4 辺すべてを描きます。barPercentage と categoryPercentage がバーの太さと間隔を合わせて制御します。
new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [10, 20, 15],
backgroundColor: '#FF6384',
borderColor: '#fff',
borderWidth: 2,
borderRadius: 8, // rounded corners (px or %)
borderSkipped: false, // draw border on all sides
barPercentage: 0.8, // bar width within category
categoryPercentage: 0.7 // category width
}]
}
});フローティングバー([min, max])
データ値として [min, max] のペアを渡すと、ゼロから始まらないフローティングバーになります — 日々の気温の最高-最低、始値-終値、信頼区間のような範囲に最適です。範囲バーでは y 軸をゼロから始めてはいけません。横棒グラフでも使えま す。
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Mon', 'Tue', 'Wed'],
datasets: [{
label: 'Low-High temp',
// each value is [min, max] -> a floating bar
data: [[10, 18], [12, 20], [8, 15]],
backgroundColor: 'rgba(75,192,192,0.6)'
}]
},
options: { scales: { y: { beginAtZero: false } } }
});折れ線グラフ
基本の折れ線グラフ
折れ線グラフはデータポイントを順番に結びます。borderColor が線の色で、backgroundColor は塗りに使われます(fill が有効な場合)。tension(0〜1)が曲線の滑らかさを制御します — 0 は直線セグメント、0.3〜0.4 程度で穏やかなベジェ曲線になります。株価のような正確なデータには 0 を使いましょう。
new Chart(ctx, {
type: 'line',
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
datasets: [{
label: 'Visitors',
data: [30, 45, 28, 60, 52],
borderColor: 'rgba(75,192,192,1)',
backgroundColor: 'rgba(75,192,192,0.2)',
tension: 0.3
}]
},
options: { scales: { y: { beginAtZero: true } } }
});複数の折れ線
折れ線グラフの各 dataset は独自の線になり、デフォルトパレットから色が自動割り当てされます(borderColor で上書き可能)。線は dataset の順に描かれるため、最後の dataset が最上面に来ます。凡例が識別できるよう、各 dataset に label を渡しましょう。
new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr'],
datasets: [
{ label: 'Plan', data: [10, 20, 25, 30], borderColor: 'red' },
{ label: 'Actual', data: [8, 22, 24, 33], borderColor: 'blue' }
]
},
options: {
scales: { y: { beginAtZero: true } },
plugins: { legend: { position: 'top' } }
}
});線の張りと補間
tension はベジェの平滑化を加えますが、データポイントを飛び越える(最小値を下回る凹みを作る)ことがあります。cubicInterpolationMode: 'monotone' は飛び越えなしで滑らかにします — 株価のような単調なデータに推奨です。borderDash は [破線長, 間隔] のパターンで、破線/点線を作ります。
datasets: [{
data: [1, 5, 2, 6, 3],
tension: 0, // straight lines
// tension: 0.4, // smooth bezier
cubicInterpolationMode: 'monotone', // no overshoot
borderDash: [5, 5], // dashed line
borderWidth: 2,
borderColor: 'purple'
}]塗りつぶし線(fill)
fill は線の下の領域を制御します。true/'origin' は x 軸まで塗り下ろします。数値(1、-1、+1)はインデックスで別の dataset に向けて塗るため、バンドチャートに有用です。負の数は前の dataset に向けて塗ります。塗りの中でも線が見えるよう、alpha 付きの backgroundColor を設定しましょう。
datasets: [
{ label: 'A', data: [3,5,4,6], fill: true, backgroundColor: 'rgba(255,99,132,0.3)' },
{ label: 'B', data: [1,2,3,2], fill: 'origin', backgroundColor: 'rgba(54,162,235,0.3)' },
{ label: 'C', data: [2,4,3,5], fill: 1, backgroundColor: 'rgba(75,192,192,0.3)' }
]
// fill values: false | true/'origin' | 1/-1/+1 | '-1' | {target:...}ポイントのスタイリング
ポイントのプロパティは単一の値か配列(データポイントごとに 1 つ)を受け付けます。pointStyle は多くの形状に対応します('circle'、'rect'、'rectRot'、'triangle'、'star'、'cross'、'crossRot')。pointRadius: 0 でポイントを完全に隠せ(密度の高い折れ線グラフに便利)、pointHoverRadius を大きくするとインタラクティブなポップ効果になります。
datasets: [{
data: [4, 6, 5, 7],
showLine: true,
pointRadius: 5, // point size (0 hides points)
pointHoverRadius: 9,
pointBackgroundColor: 'white',
pointBorderColor: 'black',
pointBorderWidth: 2,
pointStyle: 'rectRot', // 'circle','rect','triangle','star','cross'...
// per-point arrays also work:
// pointRadius: [0, 0, 6, 0],
}]ギャップの接続と欠損データ
null、undefined、NaN は欠損データを表し、デフォルトでは線を分断します。spanGaps: true でギャップの両側のポイントを 1 セグメントで結べます。NaN(欠損)と 0(実際のゼロ)を区別しましょう — 混同は誤解を招くチャートのよくある原因です。
datasets: [{
data: [5, null, 7, NaN, 9, undefined, 11],
spanGaps: true, // connect across null/NaN gaps
// spanGaps: false -> the line breaks at missing points
}]
// also skip points entirely by setting them to NaN
// NaN is "no data"; 0 is a legitimate zero value円グラフとドーナツチャート
基本の円グラフ
円グラフは全体の中の割合を示します:各値が、その割合に比例した角度のくさびになります。スライスごとに 1 つの backgroundColor(配列)を与えないと、Chart.js がデフォルトパレットを順に使います。円グラフは 3〜6 カテゴリで最もうまく機能します — それ以上は読めません。
new Chart(ctx, {
type: 'pie',
data: {
labels: ['Rent', 'Food', 'Fun', 'Save'],
datasets: [{
data: [1200, 600, 400, 800],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0']
}]
}
});基本のドーナツチャート
ドーナツは中央に穴のある円グラフです。cutout プロパティ(パーセンテージ文字列かピクセル数)が穴の大きさを制御します — '50%' が定番のドーナツの見た目です。中央の穴はプラグイン経由でサマリーラベルを持てます。リングの長さはくさびの角度よりわずかに値を捉えやすくなります。
new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [40, 35, 25],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'],
cutout: '50%' // size of the inner hole
}]
}
});Cutout、Rotation、Circumference
rotation が開始角度を度で設定します(デフォルト 0 = 右、-90 = 上)。circumference は円のどれだけを描くかを制御します — 180 で半分のドーナツになり、ゲージ風チャートに有用です。v3+ ではどちらも options の下に置きます(dataset ではなく)が、cutout はどちらにも置けます。
new Chart(ctx, {
type: 'doughnut',
data: { labels: ['A','B','C'], datasets: [{ data: [30,40,30], backgroundColor: ['#f00','#0f0','#00f'] }] },
options: {
cutout: '60%',
rotation: -90, // start at top (degrees)
circumference: 360 // full circle; 180 = half doughnut
}
});罫線とオフセット
borderColor と borderWidth はくさびを視覚的に分離します(白い罫線できれいな分割感が出ます)。hoverOffset はユーザーがホバーしたときスライスを外側へ押し出し、はっきりしたインタラクティブフィードバックを与えます。offset は配列(スライスごとに 1 つ)で、特定のくさびを恒久的に「爆発」させて強調できます。
datasets: [{
data: [30, 40, 30],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'],
borderColor: 'white',
borderWidth: 3,
hoverOffset: 16, // pop slice out on hover
offset: [0, 20, 0] // permanently offset 2nd slice
}]半ドーナツ(ゲージ)
半ドーナツ(rotation: -90、circumference: 180)はゲージ/進捗メーターとして読めます。中央テキストのプラグインと組み合わせてパーセンテージを表示し、きれいな KPI 見た目のために凡例は無効にしましょう。中立グレーの「残り」スライスが未完了部分を伝えます。
new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Done', 'Remaining'],
datasets: [{
data: [72, 28],
backgroundColor: ['#4BC0C0', '#E0E0E0']
}]
},
options: {
rotation: -90,
circumference: 180,
plugins: { legend: { display: false } }
}
});ツールチップのパーセンテージコールバック
円/ドーナツのツールチップはデフォルトで生の値を表示します。tooltip の callbacks.label でパーセンテージを計算して表示するようにしましょう — ctx.parsed がスライスの値で、ctx.dataset.data に合計のための全値が入ります。このチートシートのコード文字列に埋め込む際、コールバック内のテンプレートリテラルはバッククォートと ${} をエスケープする必要があります。
options: {
plugins: {
tooltip: {
callbacks: {
label: (ctx) => {
const total = ctx.dataset.data.reduce((a, b) => a + b, 0);
const pct = (ctx.parsed / total * 100).toFixed(1);
return `${ctx.label}: ${ctx.parsed} (${pct}%)`;
}
}
}
}
}レーダーチャート
基本のレーダーチャート
レ ーダーチャートは各ラベルを多角形の頂点として配置し、それらを閉じた形状に結びます。fill: true で内部を塗ります。放射スケールは scales.r(x/y ではなく)で設定します。レーダーは多変量のプロファイルを比較できますが、軸が多すぎたり比較できない単位だったりすると誤解を招きます。
new Chart(ctx, {
type: 'radar',
data: {
labels: ['Speed', 'Power', 'Range', 'Comfort', 'Price'],
datasets: [{
label: 'Model X',
data: [8, 7, 6, 9, 5],
borderColor: 'rgba(255,99,132,1)',
backgroundColor: 'rgba(255,99,132,0.2)',
fill: true
}]
},
options: { scales: { r: { beginAtZero: true } } }
});レーダーのスタイリング
レーダーの dataset は折れ線グラフと同じスタイリングを受け付けます:borderColor、fill、ポイントスタイル、tension。小さな tension(0.1)で頂点がわずかに丸まり柔らかい見た目になり、0 はまっすぐなスパイクを保ちます。重なり合うレーダー形状が見えるよう、半透明の backgroundColor を使いましょう。
datasets: [{
data: [7, 8, 6, 9, 5],
borderColor: 'blue',
backgroundColor: 'rgba(0,0,255,0.2)',
borderWidth: 2,
pointRadius: 4,
pointBackgroundColor: 'blue',
fill: true,
tension: 0.1 // slight curve between vertices
}]レーダースケール(r)の設定
放射スケール r がリングとラベルを制御します。min/max は全軸にわたる値の範囲を固定します(dataset を比較するときは必須)。ticks.stepSize がリングの間隔を設定し、pointLabels が周囲のカテゴリ名を整形します。リングの数字がグリッド線を遮らないよう ticks.backdropColor を透明にしましょう。
options: {
scales: {
r: {
min: 0,
max: 10,
ticks: { stepSize: 2, backdropColor: 'transparent' },
pointLabels: { font: { size: 13 }, color: '#333' },
grid: { color: '#ccc' },
angleLines: { color: '#ccc' }
}
}
}複数 dataset のレーダー
複数の dataset は同心円状の多角形として重なり、ビフォー/アフターの比較や競合比較に最適です。形状を比較可能にするため r に必ず同じ min/max を設定し、重なり部分でも両方のプロファイルが見えるよう半透明の塗りを使いましょう。
new Chart(ctx, {
type: 'radar',
data: {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [
{ label: 'Before', data: [5,6,4,7,5], borderColor: 'red', backgroundColor: 'rgba(255,0,0,0.15)', fill: true },
{ label: 'After', data: [7,8,6,9,7], borderColor: 'blue', backgroundColor: 'rgba(0,0,255,0.15)', fill: true }
]
}
});レーダーの角度線とグリッド
angleLines は中心から各頂点への放射線で、grid は同心円状の多角形リングです。ticks を隠す(display:false)と、リング自体を保ったまま数字のリングラベルが消えてよりきれいになります。pointLabels は各頂点のカテゴリテキストだけを制御します。
options: {
scales: {
r: {
angleLines: { display: true, color: 'rgba(0,0,0,0.2)', lineWidth: 1 },
grid: { display: true, color: 'rgba(0,0,0,0.1)' },
pointLabels: { display: true, color: '#000', font: { weight: 'bold' } },
ticks: { display: false } // hide numeric ring labels for a cleaner look
}
}
}ポーラーエリアチャート
基本のポーラーエリアチャート
ポーラーエリアチャートは各値を同じ角度にわたる扇形として描き、半径が値を符号化します。pie(角度 = 値)と違い、ここでは半径 = 値なので、すべての扇形は同じ角度幅で異なる長さになります。
new Chart(ctx, {
type: 'polarArea',
data: {
labels: ['North', 'South', 'East', 'West'],
datasets: [{
data: [11, 16, 7, 14],
backgroundColor: ['#FF6384', '#4BC0C0', '#FFCE56', '#36A2EB']
}]
},
options: { scales: { r: { beginAtZero: true } } }
});ポーラーエリアと円グラフの違い
重要な違い:円グラフでは各スライスの「角度」が値に比例しますが、ポーラーエリアでは各スライスの「半径」が値に比例し、角度は等しくなります。すべてのカテゴリを均等に見せつつ、大きさでサイズを示したいときにポーラーエリアを使いましょう。
// PIE: angle = value, radius = constant
new Chart(ctx, { type: 'pie', data: { datasets: [{ data: [10, 20, 30] }] } });
// POLAR: angle = constant, radius = value
new Chart(ctx, { type: 'polarArea', data: { datasets: [{ data: [10, 20, 30] }] } });
// polar area is better when values differ widely AND
// you want every category to occupy an equal angular shareポーラースケール(r)
ポーラーエリアは全扇形が共有する単一の放射スケール r を使います — つまりすべての値が同じ最大半径に対して測られます。明示的な max を設定するとチャートのスケールが正直になります。なければ Chart.js は最大値へ自動スケールし、小さな差を誇張することがあります。
options: {
scales: {
r: {
min: 0,
max: 20,
ticks: { stepSize: 5 },
grid: { color: 'rgba(0,0,0,0.15)' },
angleLines: { color: 'rgba(0,0,0,0.15)' }
}
}
}ポーラーの罫線スタイリング
ポーラーエリアの扇形は円/ドーナツと同じ罫線/塗りのスタイリングを受け付けます。白い罫線が隣接する扇形をはっきり分離します。hoverBackgroundColor はホバー時に扇形の塗りを変え、インタラクティブなフィードバックを与えます。ドーナツと違い cutout はなく — 扇形は中心で接します。
datasets: [{
data: [11, 16, 7, 14],
backgroundColor: ['#FF6384', '#4BC0C0', '#FFCE56', '#36A2EB'],
borderColor: 'white',
borderWidth: 2,
hoverBackgroundColor: '#333'
}]ホバーオフセット付きポーラー
ポーラーエリアは hoverBackgroundColor と hoverBorderColor に対応しますが、扇形が放射スケールを共有するため、ドーナツのような hoverOffset / offset には対応しません。スライスの「ポップアウト」が不可欠なら、代わりにドーナツを選びましょう。ポーラーのインタラクティビティには色やツールチップの変化を使います。
datasets: [{
data: [11, 16, 7, 14],
backgroundColor: ['#FF6384', '#4BC0C0', '#FFCE56', '#36A2EB'],
hoverOffset: 12 // not supported on polarArea the same way as doughnut;
// use hoverBackgroundColor + tooltips for interactivity
}]
// for true "pop out" use 'doughnut' insteadバブルチャート
基本のバブルチャート
バブルチャートのデータポイントは {x, y, r} のオブジェクトで、x と y が座標、r がバブルの「半径」(ピクセル)です。scatter と違い、バブルのサイズが第 3 の変数を符号化します。r は半径(面積ではない)なので、2 倍の値は視覚的に 4 倍の面積になります — サイズデータを sqrt スケールすることを検討しましょう。
new Chart(ctx, {
type: 'bubble',
data: {
datasets: [{
label: 'Products',
data: [
{ x: 10, y: 20, r: 15 },
{ x: 15, y: 10, r: 10 },
{ x: 7, y: 25, r: 8 }
],
backgroundColor: 'rgba(255,99,132,0.6)'
}]
},
options: { scales: { y: { beginAtZero: true } } }
});バブルサイズのマッピング
人間は半径ではなくバブルの「面積」を知覚するため、r を割り当てる前に Math.sqrt で値を変換すると、値が 2 倍になると見た目の面積も 2 倍になります。最大のバブルが隣接バブルと重なりすぎないような除数を選びましょう。これによりチャートは知覚的に正直になります。
const raw = [{x:1,y:2,pop:1000}, {x:2,y:3,pop:5000}, {x:3,y:1,pop:20000}];
// map a real-world value to a pixel radius with sqrt scaling
// so bubble AREA (not radius) is proportional to the value
const data = raw.map(d => ({
x: d.x,
y: d.y,
r: Math.sqrt(d.pop) / 10 // tune the divisor for your dataset
}));
new Chart(ctx, { type: 'bubble', data: { datasets: [{ data }] } });ポイントごとのバブル色
他の Chart.js の dataset と同様、バブルのスタイリングプロパティは配列を受け付け、各バブルを個別にスタイルできます。これを使ってカテゴリ別にバブルを色分けしつつ、サイズが別の数値を符号化すれば、4 次元のチャート(x、y、サイズ、色)になります。
datasets: [{
data: [
{ x: 10, y: 20, r: 15 },
{ x: 15, y: 10, r: 10 }
],
// arrays give per-point styling
backgroundColor: ['rgba(255,99,132,0.6)', 'rgba(54,162,235,0.6)'],
borderColor: ['rgba(255,99,132,1)', 'rgba(54,162,235,1)'],
borderWidth: 2
}]複数のバブル dataset
複数の dataset は色の異なるバブルグループとして描画され、それぞれが凡例に現れます。グループを重ねるときは、バブルが互いを完全に覆わないよう半径を控えめに保ちましょう。alpha 半透明の塗り(0.5〜0.6)により、重なるバブルも読み取れるようになります。
new Chart(ctx, {
type: 'bubble',
data: {
datasets: [
{ label: 'Asia', data: [{x:1,y:2,r:10},{x:3,y:4,r:8}], backgroundColor: 'rgba(255,99,132,0.6)' },
{ label: 'Europe', data: [{x:2,y:5,r:12},{x:4,y:2,r:7}], backgroundColor: 'rgba(54,162,235,0.6)' }
]
}
});バブルのホバースタイリ ング
ホバー系プロパティ(hoverBackgroundColor、hoverBorderColor、hoverBorderWidth、hoverRadius)はポインタの下のバブルだけに適用されます。hoverRadius はホバー時に半径へピクセルを加え、対象のバブルをはっきりとポップさせます。ツールチップと組み合わせれば、明確なインタラクティブなフォーカスになります。
datasets: [{
data: [{x:1,y:2,r:10}],
backgroundColor: 'rgba(75,192,192,0.5)',
hoverBackgroundColor: 'rgba(75,192,192,0.9)',
hoverBorderColor: 'black',
hoverBorderWidth: 3,
hoverRadius: 2 // EXTRA radius added on hover (v3+ uses hoverRadius)
}]散布図
基本の散布図
散布図のデータポイントは {x, y} オブジェクトです(半径は不要)。x スケールは type: 'linear'(category ではなく)にしましょう — 数値の x 値が実際の位置にマッピングされます。散布図は 2 つの連続変数の相関を示す標準的なチャートです。
new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Observations',
data: [
{ x: 1.2, y: 2.3 },
{ x: 1.8, y: 3.1 },
{ x: 2.5, y: 4.0 },
{ x: 3.1, y: 4.8 }
],
backgroundColor: 'rgba(75,192,192,0.7)'
}]
},
options: { scales: { x: { type: 'linear', position: 'bottom' } } }
});多数のポイントの散布図
数千のポイントがある場合は、pointRadius を縮め(1〜2px)、半透明の backgroundColor(alpha 0.2〜0.4)を使いましょう。重なるポイントが暗い領域として密度を示します。非常に大きな dataset では、インタラクションの応答性を保つためポイントのホバーを無効化します(pointHitRadius: 0)。
const n = 2000;
const data = Array.from({ length: n }, () => ({
x: Math.random() * 100,
y: Math.random() * 100
}));
new Chart(ctx, {
type: 'scatter',
data: { datasets: [{ data, pointRadius: 1.5, backgroundColor: 'rgba(0,0,0,0.3)' }] }
});散布図のポイントスタイリング
pointStyle はデフォルトの円の他、多くの形状に対応します:'rect'、'rectRot'、'triangle'、'star'、'cross'、'crossRot'、'dash'。pointRotation は円以外の形状を回転させます。すべての point* プロパティは配列を受け付け、ポイントごとのスタイリングが可能です — 特定の観測のハイライトに有用です。
datasets: [{
data: [{x:1,y:2},{x:2,y:3}],
pointRadius: 8,
pointHoverRadius: 12,
pointStyle: 'triangle', // 'circle','rect','star','cross',...
pointBackgroundColor: 'red',
pointBorderColor: 'darkred',
pointBorderWidth: 2,
pointRotation: 45 // rotation in degrees (for shapes)
}]トレンドライン付き散布図
Chart.js には組み込みのトレンドラインがないため、回帰を計算し(ここでは最小二乗)、両端点と pointRadius:0 の 'line' dataset を追加します。line dataset の type は dataset 単位でチャートタイプを上書きします — これは混合チャートの仕組みでもあります。fill:false で線だけにできます。
// simple least-squares fit
const pts = [{x:1,y:2},{x:2,y:3.5},{x:3,y:4.2},{x:4,y:5.1}];
const n = pts.length;
const mX = pts.reduce((s,p)=>s+p.x,0)/n;
const mY = pts.reduce((s,p)=>s+p.y,0)/n;
const slope = pts.reduce((s,p)=>s+(p.x-mX)*(p.y-mY),0) / pts.reduce((s,p)=>s+(p.x-mX)**2,0);
const intercept = mY - slope*mX;
new Chart(ctx, {
type: 'scatter',
data: { datasets: [
{ data: pts, backgroundColor: 'blue' },
{ type: 'line', data: [{x:0,y:intercept},{x:5,y:slope*5+intercept}],
borderColor: 'red', pointRadius: 0, fill: false }
]}
});散布図から折れ線へ(showLine)
scatter dataset に showLine: true を付けるとポイントが線で結ばれ、数値の x 座標を使う折れ線グラフに変わります。x 値が実数(カテゴリラベルではない)であっても接続セグメントが欲しいとき — 不規則な間隔の時系列など — に正しい選択です。
new Chart(ctx, {
type: 'scatter',
data: { datasets: [{
data: [{x:1,y:2},{x:2,y:3},{x:3,y:5}],
showLine: true, // connect points with a line
borderColor: 'green',
backgroundColor: 'green',
pointRadius: 4
}]}
});データ — Dataset
Dataset の 構造
data は labels(全 dataset で共有)と datasets(系列の配列)を持ちます。各 dataset には label(凡例/ツールチップに表示)、labels と揃った data 配列、スタイリングのプロパティがあります。dataset に設定したプロパティは、配列で上書きしない限りすべてのポイントに適用されます。
data: {
labels: ['A', 'B', 'C'], // shared category labels
datasets: [
{
label: 'Series 1', // legend + tooltip label
data: [10, 20, 30], // values (one per label)
backgroundColor: 'rgba(0,0,255,0.5)',
borderColor: 'blue',
borderWidth: 1,
// ... type-specific styling
}
]
}labels と data の整列
各 dataset の data 配列は共有の labels 配列と位置的に整列します — data[i] が labels[i] の値です。data 配列が短いと、欠けた末尾が undefined になり、折れ線グラフはそれをギャップとして扱います。予想外のギャップを避けるため、labels と data は同じ長さに保ちましょう。
data: {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [
{ data: [10, 20, 30] }, // Jan=10, Feb=20, Mar=30
{ data: [5, 15] } // Jan=5, Feb=15, Mar=undefined
]
}
// data[i] always corresponds to labels[i]; a shorter data array
// leaves the remaining positions as undefined (missing data)複数の dataset
複数の dataset は並行した系列として描画されます(グループ化されたバー、複数の折れ線、重なるレーダー)。1 つの labels 配列を共有します。dataset ごとに異なる色を設定しましょう — Chart.js が色を自動で付けるのは backgroundColor を省略したときだけで、その場合でも明示的な色の方がバージョン間で予測可能です。
data: {
labels: ['Q1','Q2','Q3','Q4'],
datasets: [
{ label: '2023', data: [20,35,30,35], backgroundColor: 'rgba(255,99,132,0.6)' },
{ label: '2024', data: [25,32,34,40], backgroundColor: 'rgba(54,162,235,0.6)' },
{ label: '2025', data: [28,38,36,45], backgroundColor: 'rgba(75,192,192,0.6)' }
]
}dataset レベルのスタイリング
dataset レベルのスタイルはその dataset のすべてのポイントに適用されます。hover* 系はホバーで発動します。hidden:true で dataset を非表示で開始できます(凡例のトグルで再表示可能)。order が描画順(z-order)を制御します — 数が小さいほど後に(上面に)描かれる — 混合/重なりチャートで有用です。
datasets: [{
label: 'Revenue',
data: [10, 20, 30],
backgroundColor: 'rgba(54,162,235,0.6)',
borderColor: 'rgba(54,162,235,1)',
borderWidth: 2,
hoverBackgroundColor: 'rgba(54,162,235,0.9)',
hidden: false, // set true to hide from view + legend toggle
order: 0 // lower order draws on top
}]オブジェクトデータのパース
データがオブジェクトの配列のとき、parsing: {xAxisKey, yAxisKey} でどのフィールドが軸の値かを Chart.js に伝えます。{x, y} ペアへの手動マッピングを避けられます。キーのデフォルトは 'x' と 'y' なので、{x, y} オブジェクトは parsing 設定なしで動きます。
new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
data: [
{ name: 'Red', votes: 12 },
{ name: 'Blue', votes: 19 }
],
parsing: { xAxisKey: 'name', yAxisKey: 'votes' }
}]
}
});ポイントごとのスタイリング配列
どのスタイリングプロパティも、単一の値(全ポイントに適用)か配列(ポイントごとに 1 つ)にできます。これで特定のポイントのハイライトが可能です — 例えば backgroundColor をほとんどグレーにし、1 つだけ赤にして注意を引きます。配列の長さはデータの長さに一致させ、短い配列は循環します。
datasets: [{
data: [10, 20, 30, 40],
// every styling property accepts an array (one value per point)
backgroundColor: ['red', 'green', 'blue', 'orange'],
borderColor: ['darkred', 'darkgreen', 'darkblue', 'darkorange'],
borderWidth: [1, 2, 3, 4],
pointRadius: [3, 6, 9, 12] // (line/scatter only)
}]Options — レスポンシブとスケール
Options の構造
options はトップレベルの設定オブジェクトです。関心ごとにグループ化されます:plugins(legend/title/tooltip)、scales(x/y/r)、layout(padding)、animation、interaction(ホバーモード)、events。ほぼすべての Chart.js の挙動は、個々の dataset ではなくここで調整します。
new Chart(ctx, {
type: 'bar',
data: { /* ... */ },
options: {
responsive: true,
maintainAspectRatio: true,
plugins: { legend: {}, title: {}, tooltip: {} },
scales: { x: {}, y: {} },
layout: { padding: 10 },
animation: { duration: 800 },
interaction: { mode: 'nearest', intersect: false },
events: ['mousemove', 'click', 'touchstart']
}
});Responsive と maintainAspectRatio
responsive:true でチャートがコンテナの幅を満たし、リサイズ時に再描画します。maintainAspectRatio:false で高さが解放され、コンテナの CSS 高さが尊重されます — 両方を設定し、canvas をサイズ指定のある <div> で包みましょう。maintainAspectRatio:true(デフォルト)ではチャートは固定の幅/高さ比を保ちます。
<div style="width:100%; height:400px;">
<canvas id="c"></canvas>
</div>
<script>
new Chart(document.getElementById('c'), {
type: 'line',
data: { /* ... */ },
options: {
responsive: true, // resize with container
maintainAspectRatio: false // let the container control height
}
});
</script>スケールの概要
scales で各軸を設定します。id(x、y、r)がスケールのキーで、type がスケールクラスを選びます。主なタイプ:'category'(テキストラベル)、'linear'(数値)、'logarithmic'、'time'(日付アダプターが必要)、'radialLinear'(レーダー/ポーラー)。title.display + text で軸ラベルを追加します。
options: {
scales: {
x: { type: 'category', title: { display: true, text: 'Month' } },
y: { type: 'linear', title: { display: true, text: 'Value' },
beginAtZero: true },
r: { type: 'radialLinear' } // for radar/polarArea
}
}
// built-in scale types: category, linear, logarithmic, time,
// timeseries, radialLinearプラグインの概要
plugins は組み込みの title、legend、tooltip プラグインのほか、登録済みのカスタムプラグインのオプションをその id でまとめます。title は canvas の上にチャートタイトルを加え、legend が dataset の凡例を制御し、tooltip がホバーポップアップを制 御します。カスタムプラグインは同じ plugins オブジェクトからオプションを読みます。
options: {
plugins: {
title: { display: true, text: 'My Chart', font: { size: 18 } },
legend: { display: true, position: 'top' },
tooltip: { enabled: true, mode: 'index', intersect: false },
// a custom inline plugin:
myPlugin: { prop: 'value' }
}
}Layout(パディング)
layout.padding はチャート領域と canvas の縁の間のスペースを追加します — タイトル、軸ラベル、大きなツールチップがクリップされる場合に有用です。単一の数値は全辺を均等にパディングし、オブジェクト形式は辺ごとの値が可能です。
options: {
layout: {
padding: {
top: 10, right: 20, bottom: 10, left: 20
}
}
}
// or a single number for all four sides:
// layout: { padding: 15 }グローバルデフォルト(Chart.defaults)
Chart.defaults はグローバルのデフォルト設定を持ちます — アプリ起動時に 1 回設定すれば、すべてのチャートが継承します。ブランディング(フォントファミリー、基本色、デフォルトアニメーション)の正しい場所です。チャートごとの options は常にデフォルトを上書きするため、個別のカスタマイズも可能です。
// set once, applies to every chart created afterwards
Chart.defaults.font.family = "'Segoe UI', sans-serif";
Chart.defaults.font.size = 13;
Chart.defaults.color = '#333';
Chart.defaults.borderColor = '#ddd';
Chart.defaults.plugins.legend.labels.color = '#333';
Chart.defaults.animation.duration = 600;
// per-chart override still wins:
new Chart(ctx, { options: { font: { size: 16 } } });軸 — X と Y
線形軸
線形軸は数値を比例的にマッピングします。beginAtZero は軸を 0 から始めさせます(棒グラフには推奨)。min/max は上限値/下限値を固定し、suggestedMin/suggestedMax は Chart.js が目盛りに合わせて拡張してよいソフトなヒントです。ticks.callback でラベルのテキストをカスタマイズできます(単位の追記など)。
options: {
scales: {
y: {
type: 'linear',
beginAtZero: true,
min: 0, max: 100, // hard limits
ticks: { stepSize: 10, callback: (v) => v + '%' }
}
}
}カテゴリ軸
カテゴリ軸は固定位置にテキストラベルを表示します。棒/折れ線グラフのデフォルト x 軸です。ticks.autoSkip:false ですべてのラベルを表示させられます(そうしないと Chart.js が重なるものを削除します)。maxRotation はカテゴリが多いときラベルを傾けて重なりを防ぎます。
options: {
scales: {
x: {
type: 'category',
labels: ['Mon','Tue','Wed'], // optional; usually from data.labels
ticks: { autoSkip: false, maxRotation: 45, minRotation: 0 }
}
}
}時刻軸
時刻軸は Date オブジェクトや ISO 文字列を時間に比例してプロットし、データのない所はギャップになります。日付アダプターパッケージが必要です(chartjs-adapter-date-fns、-luxon、-dayjs)。time.unit で目盛りの粒度を固定できます('day'、'month'、'year')。なければ Chart.js が自動選択します。
# install a date adapter
npm install chart.js date-fns date-fns-tz
import 'chartjs-adapter-date-fns';
new Chart(ctx, {
type: 'line',
data: { datasets: [{ data: [
{x: new Date('2024-01-01'), y: 10},
{x: new Date('2024-02-01'), y: 20},
{x: new Date('2024-04-01'), y: 15}
]}]},
options: { scales: { x: { type: 'time', time: { unit: 'month' } } } }
});対数軸
対数軸は 10 のべきで目盛りを置きます — 桁が大きく変わるデータ(人口、価格、周波数)に不可欠です。0 や負の値は表示できません。ticks.callback で 10 のべきのラベルをコンパクトに整形できます(科学表記など)。
new Chart(ctx, {
type: 'line',
data: { datasets: [{ data: [1, 10, 100, 1000, 10000] }] },
options: {
scales: {
y: { type: 'logarithmic',
ticks: { callback: (v) => v >= 1 ? v.toExponential(0) : v } }
}
}
});軸タイトルと ticks コールバック
title.display + title.text で軸ラベルを追加します(デフォルトは常にオフ — display:true を設定)。ticks.callback は各目盛りの値を受け取り表示文字列を返すので、元データを変えずに通貨、パーセンテージ、k/M 省略形、任意のカスタムテキストへ整形できます。
options: {
scales: {
y: {
title: { display: true, text: 'Revenue (USD)', color: '#333', font: { size: 14, weight: 'bold' } },
ticks: {
callback: function(value) {
if (value >= 1000) return (value/1000) + 'k';
return value;
}
}
}
}
}min/max と suggestedMin/max の違い
min/max は「ハードな」上限値/下限値です:データが範囲を超えても軸はその内側に留ま ります(データはクリップされる)。suggestedMin/suggestedMax は「ソフトな」ヒントです:Chart.js はそれを基準にしますが、きれいな目盛り値を得るために拡張することがあります。きれいな丸い数字が欲しいなら suggested*、パーセンテージのような固定スケールにはハードな min/max を使いましょう。
options: {
scales: {
y: {
// hard limits — chart never goes outside this range
min: 0, max: 100,
// OR soft hints — Chart.js may expand to fit nice ticks:
// suggestedMin: 0, suggestedMax: 100,
ticks: { stepSize: 20 }
}
}
}凡例
凡例の基本
凡例は各 dataset の label と色見本を一覧します。display:true で表示(デフォルト)、display:false で非表示です。position は 'top'、'bottom'、'left'、'right'、'center'(chartArea)を受け付けます。凡例項目をクリックするとデフォルトでその dataset の表示がトグルされます — 組み込みのフィルタリングインタラクションです。
new Chart(ctx, {
type: 'bar',
data: { labels: ['A','B'], datasets: [{ label: 'Sales', data: [10,20] }] },
options: {
plugins: {
legend: { display: true, position: 'top' }
}
}
});凡例の位置と整列
position が凡例の辺を設定し、align がその辺上の配置を制御します('start'/'center'/'end')。labels が色見本(boxWidth/boxHeight)とテキストのスタイリングを設定します。maxWidth が凡例領域を制限し、非常に長い凡例はチャートを押し退けるのではなく折り返します。
plugins: {
legend: {
position: 'bottom',
align: 'center', // 'start' | 'center' | 'end'
maxWidth: 300,
labels: {
boxWidth: 20,
boxHeight: 20,
padding: 15,
color: '#333',
font: { size: 12 }
}
}
}凡例の onClick(カスタムトグル)
legend.onClick を上書きするとクリック動作をカスタマイズできます。デフォルトは dataset の表示トグルです。シグネチャは (event, legendItem, legend) です。状態を変えた 後に chart.update() を呼ぶと再描画されます。非表示前の確認、外部 UI との同期、単一選択(ラジオ)動作の実装に使えます。
plugins: {
legend: {
onClick(e, item, legend) {
const chart = legend.chart;
const dataset = chart.data.datasets[item.datasetIndex];
// custom: toggle visibility AND log the action
dataset.hidden = !dataset.hidden;
console.log('Toggled', dataset.label, '->', dataset.hidden);
chart.update();
}
}
}凡例ラベルのコールバック
generateLabels は凡例に現れるものを完全に制御するラベルオブジェクトの配列を返します。各項目のテキスト、色見本の色、hidden 状態をカスタマイズできます — カウントや単位の追加、dataset 以外のデータからの凡例生成に有用です。hidden フラグと datasetIndex がクリックを正しい dataset へ結びます。
plugins: {
legend: {
labels: {
generateLabels(chart) {
return chart.data.datasets.map((ds, i) => ({
text: `${ds.label} (${ds.data.length} pts)`,
fillStyle: ds.backgroundColor,
strokeStyle: ds.borderColor,
lineWidth: ds.borderWidth,
hidden: ds.hidden,
datasetIndex: i
}));
}
}
}
}凡例の非表示と外部凡例
スタイルの完全な制御のためには、組み込みの凡例を無効化し(display:false)、独自の HTML 凡例を描画しましょう。chart.data.datasets を反復してボタン/色見本を描画し、クリック時に dataset.hidden をトグルして chart.update() を呼びます。デフォルトの canvas 凡例がデザインシステムに合わないときによく使われます。
// hide the built-in legend entirely
options: { plugins: { legend: { display: false } } }
// build your own external legend HTML, then wire it to the chart:
const chart = new Chart(ctx, { /* ... */, options: { plugins: { legend: { display: false } } } });
chart.data.datasets.forEach((ds, i) => {
const btn = document.createElement('button');
btn.textContent = ds.label;
btn.onclick = () => { ds.hidden = !ds.hidden; chart.update(); };
document.getElementById('legend').appendChild(btn);
});ツールチップ
ツールチップの基本
ツールチップはホバー時に表示され、dataset のラベルと値を示します。enabled:true がデフォルトです。スタイリングプロパティ(backgroundColor、titleColor、bodyColor、padding、cornerRadius)が見た目を制御します。displayColors が各項目の横の小さな色見本をトグルします — 多くの dataset が重なるときに有用です。
options: {
plugins: {
tooltip: {
enabled: true, // show tooltips
backgroundColor: 'rgba(0,0,0,0.8)',
titleColor: 'white',
bodyColor: 'white',
borderColor: 'gray',
borderWidth: 1,
padding: 10,
cornerRadius: 4,
displayColors: true // show color boxes
}
}
}ツールチップの label コールバック
callbacks.label は各ツールチップ行のテキストを返します。ctx.dataset.label が系列名で、ctx.parsed.y が値を持ちます(pie/radar では ctx.parsed を使う)。ここで通貨の整形、単位の追記、合計の計算ができます。返した文字列(または文字列の配列)がツールチップの本文になります。
plugins: {
tooltip: {
callbacks: {
label: (ctx) => {
const label = ctx.dataset.label || '';
const value = ctx.parsed.y ?? ctx.parsed;
return `${label}: $${value}`;
}
}
}
}ツールチップの title コールバック
callbacks.title がツールチップのヘッダーを制御します(デフォルト:x 軸のラベル)。関数はツールチップ項目の配列を受け取ります(mode:'index' で複数 dataset がまとめられるとき有用)。空文字列 '' を返すとタイトルが完全に抑制されます。title と label のコールバックを組み合わせれば、完全にカスタムのツールチップコンテンツになります。
plugins: {
tooltip: {
callbacks: {
title: (items) => {
// items[0].label is the x-axis label / category
return 'Period: ' + items[0].label;
},
label: (ctx) => ctx.dataset.label + ': ' + ctx.formattedValue
}
}
}外部 HTML ツールチップ
external を使うとツールチップを実際の HTML として描画できます — canvas では不可能なリッチなスタイリング、画像、リンクのため。デフォルトのツールチップが二重描画しないよう enabled:false を設定しましょう。コールバックは、位置を示す caretX/caretY と本文行を持つ tooltip オブジェクトを含むコンテキストを受け取ります。HTML 要素をその座標に配置しましょう。
plugins: {
tooltip: {
enabled: false, // disable default canvas tooltip
external(context) {
const { tooltip } = context;
let el = document.getElementById('tt');
if (!el) { el = document.createElement('div'); el.id = 'tt'; document.body.appendChild(el); }
if (tooltip.opacity === 0) { el.style.opacity = 0; return; }
el.innerHTML = tooltip.body.map(b => b.lines.join('')).join('<br>');
el.style.position = 'fixed';
el.style.left = tooltip.caretX + 'px';
el.style.top = tooltip.caretY + 'px';
el.style.opacity = 1;
}
}
}ツールチップのモード(interaction)
interaction.mode がツールチップの対象を制御します。'point' はホバーしたポイントだけを示し、'index' は同じ x の全 dataset を示します(グループ化されたバー/折れ線に最適)、'nearest' は最も近い 1 ポイントを探します。intersect:false でポインタが列内のどこにあってもツールチップが発動します(ポイント上だけではない)— 通常はこちらがユーザーの期待どおりです。
options: {
interaction: {
mode: 'index', // 'point' | 'nearest' | 'index' | 'x' | 'y' | 'dataset'
intersect: false // trigger even when not directly over a point
},
plugins: { tooltip: { mode: 'index', intersect: false } }
}ツールチップのスタイリングとフィルタ
filter は条件を満たさないツールチップ行をスキップします(ゼロ/空の値を隠すなど)。callbacks.footer がすべての項目の後にサマリー行を加えます — 合計の表示に最適です。bodyFont/titleFont がテキストを整形し、caretSize と caretPadding が小さな矢印ポインタを制御します。
plugins: {
tooltip: {
filter: (item) => item.parsed.y !== 0, // hide zero values
callbacks: { footer: (items) => 'Total: ' + items.reduce((s,i)=>s+i.parsed.y,0) },
bodyFont: { size: 13, weight: 'bold' },
titleFont: { size: 14 },
caretSize: 6,
caretPadding: 8
}
}アニメーション
アニメーションの時間
animation.duration がアニメーションの総時間をミリ秒で設定します(デフォルト 1000)。easing が加速曲線を制御します — 'easeOutQuart'(デフォルト)は速く始まり減速するため、レスポンシブに感じられます。頻繁に更新されるデータダッシュボードでは短くしましょう(200〜400ms)。
options: {
animation: {
duration: 1000, // total duration in ms
easing: 'easeOutQuart'
}
}
// easing options: 'linear','easeInQuad','easeOutQuad','easeInOutQuad',
// 'easeInCubic','easeOutCubic','easeInOutCubic','easeOutBounce',...アニメーションの無効化
animation:false ですべてのアニメーションを完全にオフにできます — パフォーマンス重視のダッシュボードや、高速な更新を流し込むときに最適です。animation:{duration:0} はアニメーションシステムを有効のまま即時にします(ホバーは動き続けます)。複数形の animations オブジェクトで、y のように特定のプロパティだけを無効化し他はアニメーションさせられます。
// disable ALL animations
options: { animation: false }
// disable only the initial draw, keep hover animations:
options: { animation: { duration: 0 } }
// per-property: animate everything except the y axis
options: {
animations: {
y: { duration: 0 }
}
}イージング関数
イージングはアニメーションの進行の仕方を変え、感覚に大きな影響を与えます。'easeOutQuart'(デフォルト)はプロフェッショナルでレスポンシブな感覚です。'easeOutBounce' や 'easeInOutBack' は遊び心がありますが、データチャートではご都合主義的に感じられることも。アプリ全体のモーションの言葉に合わせましょう。
options: {
animation: {
duration: 1200,
easing: 'easeInOutBack' // slight overshoot for a playful feel
}
}
// common easings:
// 'linear' constant speed (mechanical)
// 'easeOutQuart' default; snappy start, smooth end
// 'easeInOutCubic' symmetric in/out
// 'easeOutBounce' bouncy landing
// 'easeInOutBack' overshoots at both endsアニメーションの onComplete
onComplete はアニメーションが終わったときに発火します — エクスポートボタンを有効化する、後続の描画をトリガーするといったアクションのチェーンに有用です。onProgress はアニメーションの毎フレームにステップ数とともに発火します。毎秒 60 回動くため、onProgress での重 い処理は避けましょう。
options: {
animation: {
onComplete: function() {
console.log('Animation finished');
// e.g. enable a "download PNG" button now that the chart is stable
document.getElementById('downloadBtn').disabled = false;
},
onProgress: function(ctx) {
// fired each frame; ctx.currentStep / ctx.numSteps
}
}
}プロパティごとのアニメーション(animations)
複数形の animations オブジェクトは個々のプロパティを独立に設定します。各エントリは from/to(またはパースコンテキストの関数)、duration、easing、loop を指定できます。tension を 1 から 0.3 へアニメーションさせると「線が整う」効果になり、y を軸の基線からアニメーションさせると「立ち上がる」効果になります。
options: {
animations: {
tension: {
duration: 1500,
easing: 'easeOutBounce',
from: 1, // start very curved
to: 0.3, // settle at a gentle curve
loop: false
},
colors: { duration: 800 },
y: { from: ctx => ctx.chart.scales.y.getPixelForValue(0) }
}
}イベントとクリック
onClick ハンドラ
options.onClick はユーザーがチャートのどこかをクリックしたときに発火します。elements 引数はクリックされたチャート要素(バー/ポイント)の配列で、それぞれ .datasetIndex と .index を持ちます。elements が空なら、クリックは空白の canvas に当たったということです。これがチャートをインタラクティブにする(ドリルダウン、選択)標準的な方法です。
new Chart(ctx, {
type: 'bar',
data: { labels: ['A','B','C'], datasets: [{ data: [10,20,30] }] },
options: {
onClick(event, elements, chart) {
if (elements.length > 0) {
const el = elements[0];
const label = chart.data.labels[el.index];
const value = chart.data.datasets[el.datasetIndex].data[el.index];
alert(`Clicked ${label} = ${value}`);
}
}
}
});getElementsAtEventForMode
getElementsAtEventForMode はネイティブのマウスイベントの下にあるチャート要素を見つけます。interaction と同じモードオプション('nearest'、'index'、'x' など)を使います。第 4 引数 useFinalPosition は、最終的に描画された位置でのヒットテストには true にします。options.onClick の外で要素を調べたいときに使います。
const chart = new Chart(ctx, { /* ... */ });
canvas.addEventListener('click', (e) => {
const points = chart.getElementsAtEventForMode(
e, 'nearest', { intersect: true }, true // (event, mode, options, useFinalPosition)
);
if (points.length) {
const p = points[0];
console.log('dataset', p.datasetIndex, 'index', p.index);
}
});onHover
options.onHover はチャート上のマウス移動のたびに発火します。カーソルを変える(表示例のような)安価な UI フィードバックや、関連する外部要素のハイライトに使います。非常に頻繁に発火するため、高コストな操作は避けましょう。重いロジックは onClick か、ハンドラの debounce で。
options: {
onHover(event, elements, chart) {
// change cursor to a pointer when hovering a bar
event.native.target.style.cursor =
elements.length ? 'pointer' : 'default';
}
}Hover とアクティブな要素
hover の設定がポインタ下の要素のハイライト方法を制御します。mode:'nearest' + intersect:true で最も近い 1 ポイントをハイライトします。animationDuration がハイライトの遷移を滑らかにします。chart.setActiveElements はホバー状態をプログラム的にトリガーします — チャートのハイライトを外部 UI と同期するのに有用です。
options: {
hover: {
mode: 'nearest',
intersect: true,
animationDuration: 200 // smooth transition when hover target changes
}
}
// programmatically set the hovered element:
chart.setActiveElements([{ datasetIndex: 0, index: 2 }]);
chart.update();イベントリスト
events がチャートが listen する DOM イベントを制限します。リストを減らす('click' だけにするなど)とホバー効果が無効になり静的な印象になり、ダッシュボードのパフォーマンスが向上します。タッチ専用のモバイルコンテキストでは touchstart/touchmove を含めましょう。空の配列ですべてのインタラクションが無効になります。
options: {
events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove']
// restrict to just click for a non-interactive "static" feel:
// events: ['click']
}
// supported events: mousemove, mouseout, click, touchstart, touchmove,
// touchend, pointer events (Chart.js v3.4+)ドリルダウンの例
よくあるパターン:バーをクリックすると dataset をより詳細なビューに差し替えます(ドリルダウン)。クリックされたインデックスを取り、chart.data.labels と chart.data.datasets[...].data を置き換え、chart.update() を呼ぶと遷移がアニメーションします。戻るボタンが欲しければ、ビューのスタックを保持しましょう。
const monthly = { labels: ['Jan','Feb','Mar'], data: [100,120,90] };
const daily = { labels: Array.from({length:28},(_,i)=>'D'+(i+1)),
data: Array.from({length:28},()=>Math.random()*50) };
const chart = new Chart(ctx, {
type: 'bar',
data: { labels: monthly.labels, datasets: [{ data: monthly.data }] },
options: { onClick(evt, els) {
if (!els.length) return;
const idx = els[0].index;
chart.data.labels = daily.labels;
chart.data.datasets[0].data = daily.data;
chart.update();
}}
});混合チャート
バー + 折れ線の混合チャート
個々の dataset に type を設定すればチャートタイプを混在させられます — その系列についてチャートレベルの type を上書きします。バー + 折れ線の組み合わせが最も一般的なミックスです(例:棒は売上、線は成長率)。系列の単位やスケールが異なるときは 2 つ目の y 軸(y1)を使いましょう。
new Chart(ctx, {
type: 'bar', // default type for all datasets
data: {
labels: ['Jan','Feb','Mar','Apr'],
datasets: [
{ type: 'bar', label: 'Revenue', data: [20,35,30,40], backgroundColor: '#36A2EB', yAxisID: 'y' },
{ type: 'line', label: 'Growth', data: [5,8,6,12], borderColor: '#FF6384', yAxisID: 'y1', fill: false }
]
},
options: { scales: { y: { position: 'left' }, y1: { position: 'right', grid: { drawOnChartArea: false } } } }
});dataset の type 上書き
どの dataset もチャートレベルの type を上書きでき、1 つのチャートに bar、line、scatter を組み合わせられます。明示的な type のない dataset はチャートの type を継承します。z-order に注意しましょう:dataset は配列の順に描かれるため、背景の系列(バー)を手前の系列(線)の前に置きます。
new Chart(ctx, {
type: 'line', // chart-level default
data: {
labels: ['A','B','C'],
datasets: [
{ data: [1,2,3] }, // inherits 'line'
{ type: 'bar', data: [3,2,1] }, // becomes a bar
{ type: 'scatter', data: [{x:0,y:2},{x:2,y:3}], pointRadius: 5 } // scatter points
]
}
});複数の Y 軸(y、y1、y2)
カスタム id(y、y1、y2)で複数の y 軸を定義し、yAxisID で dataset を割り当てます。grid.drawOnChartArea:false で 2 つ目の軸が 1 つ目の上にグリッド線を描くのを防げます。position:'right' で右に重ね、3 つ目の軸には offset:true を加えて 2 つ目と重ならないようにします。系列に合わせて各軸に色を付けましょう。
options: {
scales: {
y: { type: 'linear', position: 'left', title: { display: true, text: 'Price ($)' } },
y1: { type: 'linear', position: 'right', title: { display: true, text: 'Volume' }, grid: { drawOnChartArea: false } },
y2: { type: 'linear', position: 'right', offset: true, title: { display: true, text: '%' } }
}
}
// assign each dataset: yAxisID: 'y' | 'y1' | 'y2'異なる形状の混合データ
混合チャートは値の系列(バー)と参照線(一定のターゲット、トレンド)を組み合わせられます。line dataset に pointRadius:0 と fill:false を付けると、マーカーや塗りのない純粋な線として描画されます。このパターンはパフォーマンスダッシュボード(実績 vs 目標)でよく使われます。
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Mon','Tue','Wed','Thu','Fri'],
datasets: [
{ type:'bar', label:'Tasks', data:[8,6,7,9,5], backgroundColor:'rgba(54,162,235,0.6)' },
{ type:'line', label:'Target',data:[7,7,7,7,7], borderColor:'red', borderWidth:2, pointRadius:0, fill:false },
{ type:'line', label:'Trend', data:[6,6.5,7,8,8.5], borderColor:'green', borderDash:[5,5], pointRadius:0, fill:false }
]
}
});混合スタイリングのヒント
混合チャートでは dataset.order を設定して、線がバーの上に描かれるようにしましょう(order が小さいほど上面)。読者がどのスケールがどの線に属するか分かるよう、各軸の目盛りとタイトルをその系列に合わせて色分けします。二重のグリッド線を避けるため、2 つ目の軸のグリッドは無効化します(drawOnChartArea:false)。
// 1. assign order so lines draw on top of bars
datasets: [
{ type:'bar', data:[...], order: 2 },
{ type:'line', data:[...], order: 1 } // lower order draws later (on top)
]
// 2. give each axis a matching color
options: { scales: {
y: { ticks: { color: '#36A2EB' }, title: { text: 'Revenue', color: '#36A2EB' } },
y1: { ticks: { color: '#FF6384' }, title: { text: 'Growth', color: '#FF6384' }, position: 'right', grid: { drawOnChartArea: false } }
}}プラグイン
組み込みプラグイン
Chart.js には 3 つの組み込みプラグインがあります:Title(canvas 上のチャートタイトル)、Legend(dataset の凡例)、Tooltip(ホバーポップアップ)。options.plugins の下でその id で設定され、デフォルトで有効です(Title だけはテキストを表示するのに display:true が必要)。
// three built-in plugins (always available):
// Legend -> options.plugins.legend
// Title -> options.plugins.title
// Tooltip -> options.plugins.tooltip
new Chart(ctx, {
type: 'line',
data: { /* ... */ },
options: {
plugins: {
title: { display: true, text: 'Sales 2024', font: { size: 18 } },
legend: { position: 'bottom' },
tooltip:{ mode: 'index', intersect: false }
}
}
});カスタムインラインプラグイン
plugins オプション経由で、単一のチャートへプラグインオブジェクトの配列を渡せます。各プラグインは id とフック関数(beforeInit、afterInit、beforeDraw、afterDraw、beforeUpdate など)を持ちます。インラインプラグインはそのチャートインスタンスにだけ適用されます。canvas 状態の変更は ctx.save()/restore() で挟みましょう。
new Chart(ctx, {
type: 'line',
data: { /* ... */ },
options: { /* ... */ },
plugins: [{
id: 'centerText',
afterDraw(chart) {
const { ctx, chartArea } = chart;
ctx.save();
ctx.font = 'bold 24px Arial';
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('Hello', (chartArea.left+chartArea.right)/2,
(chartArea.top+chartArea.bottom)/2);
ctx.restore();
}
}]
});プラグインフック(ライフサイクル)
プラグインフックはチャートライフサイクルの各段階で動きます:init、update、render、draw、resize、destroy。before* 系フックは false を返すことでアクションをキャンセルできます。カスタム描画で最もよく使うのは、afterDraw(チャートの上に描く)か beforeDraw(データの後ろに描く)です。各フックはチャートインスタンスを受け取ります。
const plugin = {
id: 'myHook',
beforeInit(chart) { console.log('before init'); },
afterInit(chart) { console.log('chart ready'); },
beforeUpdate(chart){ console.log('about to update'); },
beforeDraw(chart) { console.log('before draw'); },
afterDraw(chart) { console.log('after draw'); },
beforeRender(chart){ console.log('before first render'); },
resize(chart, size){ console.log('resized', size); },
destroy(chart) { console.log('destroyed'); }
};プラグイン:インデックス位置の縦線
よくあるカスタムプラグインは、ツールチップの位置に縦のガイドラインを描きます(デフォルトの十字線のように)。afterDraw がアクティブなツールチップ要素の x 座標を読み、チャート領域の上から下まで破線を引きます。破線スタイルが漏れないよう、canvas 状態を save()/restore() で挟みましょう。
const verticalLine = {
id: 'verticalLine',
afterDraw(chart) {
if (chart.tooltip?._active?.length) {
const x = chart.tooltip._active[0].element.x;
const { top, bottom } = chart.chartArea;
const ctx = chart.ctx;
ctx.save();
ctx.beginPath();
ctx.moveTo(x, top);
ctx.lineTo(x, bottom);
ctx.lineWidth = 1;
ctx.strokeStyle = 'gray';
ctx.setLineDash([4, 4]);
ctx.stroke();
ctx.restore();
}
}
};プラグイン:ドーナツの中央テキスト
中央にサマリーテキストを描くことは、ドーナツプラグインの定番のユースケースです。afterDatasetsDraw はくさびの後に動くため、テキストがその上に乗ります。合計(または任意のサマリー)を計算し、chartArea の幾何学的中心に描画します。これでドーナツが情報豊かな KPI ウィジェットになります。
const centerText = {
id: 'centerText',
afterDatasetsDraw(chart) {
const { ctx, data } = chart;
const total = data.datasets[0].data.reduce((a,b)=>a+b, 0);
ctx.save();
ctx.font = 'bold 28px Arial';
ctx.fillStyle = '#333';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const { left, right, top, bottom } = chart.chartArea;
ctx.fillText(total, (left+right)/2, (top+bottom)/2);
ctx.restore();
}
};
new Chart(ctx, { type:'doughnut', data:{...}, plugins:[centerText] });プラグインのグローバル登録
Chart.register(plugin) でプラグインが以後に作られるすべてのチャートに適用されます — ウォーターマーク、ブランディング、分析のようなアプリ全体のプラグインに最適です。1 回だけのチャートにはインラインの plugins 配列を使いましょう。Chart.unregister で解除します。登録されたプラグインは options.plugins[id] から設定を読みます。
import { Chart } from 'chart.js';
const myPlugin = { id: 'watermark', afterDraw(chart) { /* ... */ } };
// register once -> applies to EVERY chart
Chart.register(myPlugin);
// or unregister later
Chart.unregister(myPlugin);
// per-chart-only: skip Chart.register and pass via options.plugins instead更新と破棄
chart.update()
chart.data や chart.options を書き換えた後 、chart.update() を呼んで再描画します。デフォルトでは前の状態からアニメーションします。アニメーションをスキップするにはモードに 'none' を渡します(高頻度の更新に有用)。書き換えて更新する方が、破壊して再作成するよりはるかに安価です。
const chart = new Chart(ctx, config);
// mutate the data/config, then update:
chart.data.labels.push('Jun');
chart.data.datasets[0].data.push(28);
chart.options.scales.y.max = 50;
chart.update(); // animate to the new state
// chart.update('none'); // skip animation更新モード
update(mode) は挙動を制御するモード文字列を受け付けます。'none' はアニメーションなしのサイレントな更新です。'reset' はアニメーション前の値へ巻き戻してから再アニメーションします(登場演出のリプレイに良い)。'active' はホバーされた要素だけを更新し、安価なホバー再描画に使えます。デフォルト(引数なし)は通常どおりアニメーションします。
chart.update(); // default: animates the change
chart.update('none'); // no animation
chart.update('reset'); // reset to pre-animation state, then animate
chart.update('resize'); // re-compute layout (call after container resize)
chart.update('show'); // show currently-hidden dataset animations
chart.update('hide'); // hide dataset animations
chart.update('active'); // update only the active (hovered) elementsデータとラベルの更新
data/labels は丸ごと差し替えも、その場での書き換え(push/shift)もできます。ライブストリーミングチャート(60 秒の窓など)では、新しい値を追加し最も古いものを shift して、update('none') で滑らかな非アニメーション更新にしましょう — 毎ティックでデフォルトのアニメーション付き更新を呼ぶと、ギクシャクした遅れの原因になります。
// replace the entire data array
chart.data.datasets[0].data = [5, 10, 15, 20];
chart.data.labels = ['A','B','C','D'];
chart.update();
// or append streaming data (and trim the oldest):
const arr = chart.data.datasets[0].data;
arr.push(newValue);
if (arr.length > 60) arr.shift();
chart.update('none'); // instant update for live datachart.destroy()
destroy() はチャートを取り壊します:イベントリスナーを取り除き、アニメーションをキャンセルし、canvas を消去し、メモリを解放します。チャートのコンテナが取り除かれるときは必ず destroy を呼びましょう(React の useEffect クリーンアップ、ルート変更)。destroy を怠るとメモリリークし、canvas を再利用するときに「Canvas is already in use」エラーが投げられることがあります。
const chart = new Chart(ctx, config);
// when done (route change, component unmount, etc.):
chart.destroy();
// after destroy the canvas is free; a new Chart can reuse it:
const fresh = new Chart(ctx, newConfig);
// destroy also removes event listeners and frees memorychart.resize() と clear()
chart.resize() はチャートのサイズを再計算します — responsive:true ならウィンドウのリサイズで自動的に行われるため、手動呼び出しはまれです。chart.clear() はチャートを破壊せずに canvas を真っ白にします(次の update で再描画)。chart.resize(width, height) は特定のピクセル寸法を強制し、レスポンシブなサイズ決定を上書きします。
const chart = new Chart(ctx, config);
// manually trigger a resize (rarely needed; responsive:true auto-resizes)
chart.resize();
// clear the canvas (chart stays alive, just blank until next render):
chart.clear();
chart.draw(); // re-draw without recomputing layout
// resize the canvas to explicit dimensions:
chart.resize(800, 400);レスポンシブと devicePixelRatio
レスポンシブコンテナ
レスポンシブなチャートには、明示的な width/height を持つ配置済みコンテナで canvas を包み、responsive:true + maintainAspectRatio:false を設定しましょう。canvas がコンテナを満たし、ウィンドウリサイズで再描画します。maintainAspectRatio:false がないと、チャートは固定のアスペクト比を保ち、コンテナの高さを無視します。
<!-- container controls the size -->
<div style="position: relative; width: 100%; height: 400px;">
<canvas id="c"></canvas>
</div>
<script>
new Chart(document.getElementById('c'), {
type: 'line',
data: { /* ... */ },
options: { responsive: true, maintainAspectRatio: false }
});
</script>maintainAspectRatio
maintainAspectRatio:true(デフォルト)は、aspectRatio(デフォルト 2 = 2:1)で設定された固定の幅/高さ比を保ちます。maintainAspectRatio:false で高さをコンテナへ解放します。pie/doughnut はデフォルトで aspectRatio:1(正方形)です — 円は横長の長方形では変に見えるためです。
// default: chart keeps a 2:1 (width:height) aspect ratio
options: { responsive: true, maintainAspectRatio: true, aspectRatio: 2 }
// let the container control height:
options: { responsive: true, maintainAspectRatio: false }
// square charts:
options: { responsive: true, maintainAspectRatio: true, aspectRatio: 1 }aspectRatio
aspectRatio = 幅 / 高さです。maintainAspectRatio:true のとき、canvas の寸法はこの比に従います。幅広のダッシュボードタイルには高い比(3〜4)、縦長のパネルには低い比(1〜1.5)を使いましょう。pie/doughnut が 1 なのは、円が楕円に見えないよう正方形の canvas が必要だからです。
new Chart(ctx, {
type: 'bar',
data: { /* ... */ },
options: {
responsive: true,
maintainAspectRatio: true,
aspectRatio: 3 // width:height = 3:1 (wide, short chart)
}
});
// common ratios:
// 2 -> default for bar/line
// 1 -> pie/doughnut (square)
// 3 -> wide dashboards
// 16/9 -> video-likechart.resize() メソッド
Chart.js は responsive:true のときウィンドウのリサイズイベントを自動的に listen しますが、CSS トランジション、サイドバーの開閉、タブ切り替えによるレイアウト変更はウィンドウのリサイズを発火させないことがあります。そのような場合は、コンテナのサイズが確定した後に(setTimeout や transitionend のハンドラなどで)chart.resize() を手動で呼びましょう。
const chart = new Chart(ctx, { /* responsive: true */ });
// manually trigger a re-layout (e.g. after a sidebar collapses)
window.dispatchEvent(new Event('resize'));
// or:
chart.resize();
// explicit size:
chart.resize(600, 300);devicePixelRatio(鮮明な描画)
devicePixelRatio が canvas のバッキングストアを拡大し、高 DPI/retina ディスプレイでも線が鮮明に保たれます(デフォルトは window.devicePixelRatio を使用、通常 2 か 3)。2 で上限を設けると、3x のスマホでのピクセル負荷を抑えつつテキストをくっきり保てます。1 に設定すると retina ではぼやけますが、描画速度が最大化されます。
// let Chart.js use the screen's full pixel density (default):
new Chart(ctx, { options: { devicePixelRatio: window.devicePixelRatio } });
// cap DPR for performance on retina displays (fewer pixels to render):
options: { devicePixelRatio: 2 }
// ignore DPR (renders at 1x — blurry on retina but fastest):
options: { devicePixelRatio: 1 }ResizeObserver パターン
チャートのコンテナへの ResizeObserver は、ウィンドウリサイズでは捕捉されない、CSS flexbox/grid、折りたたみサイドバー、タブ切り替えによるサイズ変更を捉えます。リークを防ぐため、後始末で observer の disconnect と chart.destroy() を呼びましょう。複雑なレイアウトに対する最も堅牢なレスポンシブパターンです。
const canvas = document.getElementById('c');
const chart = new Chart(canvas, config);
// observe the CONTAINER, not the canvas:
const ro = new ResizeObserver(() => chart.resize());
ro.observe(canvas.parentElement);
// cleanup on destroy:
function teardown() {
ro.disconnect();
chart.destroy();
}関連する Chart.js スニペット
Copy-paste ready code for common tasks.
Bar Chart
Vertical bar chart with custom colors and rounded corners.
Line Chart
Smooth line chart with fill, tension, and hover styling.
Pie Chart
Pie chart with per-slice colors and legend positioning.
Doughnut Chart
Doughnut chart with cutout control and centered title.
Radar Chart
Multi-series radar chart for comparing entities across dimensions.
Responsive Chart
Chart that fills its container with maintainAspectRatio disabled.
Options Configuration
Title, legend, axis formatting, animations, and live updates.
Tooltips
Custom-styled tooltips with title, label, and footer callbacks.
Was this helpful?