散布図を描画する (Highchartsを利用) - JavaScript
Highchartsを利用して散布図を描画するコードを紹介します。
事前準備
Highchartsをインストールします。手順は
こちらの記事を参照してください。
実装例
コード
以下のHTMLファイルを作成します。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="ScatterPlot.css" />
<script src="js/highcharts/highcharts.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
Highcharts.setOptions({
colors: [
'rgba(17,152,222,1)', 'rgba(222,17,205,1)'
]
});
const series = [{
name: 'Group1',
id: 'Group1',
marker: {
symbol: 'circle'
}
},
{
name: 'Group2',
id: 'Group2',
marker: {
symbol: 'circle'
}
}];
const temp1 = [];
temp1.push([25, 15]);
temp1.push([22, 38]);
temp1.push([38, 25]);
temp1.push([38, 20]);
temp1.push([30, 25]);
const temp2 = [];
temp2.push([8, 21]);
temp2.push([14, 10]);
temp2.push([5, 12]);
temp2.push([21, 18]);
temp2.push([16, 22]);
series[0].data = temp1;
series[1].data = temp2;
Highcharts.chart('container', {
chart: {
type: 'scatter',
zooming: {
type: 'xy'
}
},
title: {
text: 'Demo Title',
align: 'left'
},
subtitle: {
text: 'Demo Subtitle',
align: 'left'
},
xAxis: {
title: {
text: 'intelligence'
},
labels: {
format: '{value} point'
},
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
text: 'physical'
},
labels: {
format: '{value} point'
}
},
legend: {
enabled: true
},
plotOptions: {
scatter: {
marker: {
radius: 2.5,
symbol: 'circle',
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
jitter: {
x: 1
}
}
},
tooltip: {
pointFormat: 'Height: {point.x} m <br/> Weight: {point.y} kg'
},
series
});
}
);
</script>
</head>
<body>
<h1>散布図の描画のデモ</h1>
<div id="container" style="width:480px; height:480px;"></div>
</body>
</html>
解説
グラフの情報はJSONオブジェクト形式で記述します。
以下は散布図のドットの色を設定しています。今回2つのグループ(系列)の散布図を描画します。
Highcharts.setOptions({
colors: [
'rgba(17,152,222,1)', 'rgba(222,17,205,1)'
]
});
系列の設定をします。系列名とIDの値を設定します。散布図のドットの形状を設定します。
今回は円形で描画します。
const series = [{
name: 'Group1',
id: 'Group1',
marker: {
symbol: 'circle'
}
},
{
name: 'Group2',
id: 'Group2',
marker: {
symbol: 'circle'
}
}];
散布図のデータを設定します。
const temp1 = [];
temp1.push([25, 15]);
temp1.push([22, 38]);
temp1.push([38, 25]);
temp1.push([38, 20]);
temp1.push([30, 25]);
const temp2 = [];
temp2.push([8, 21]);
temp2.push([14, 10]);
temp2.push([5, 12]);
temp2.push([21, 18]);
temp2.push([16, 22]);
series[0].data = temp1;
series[1].data = temp2;
グラフの設定をします。今回は散布図のため、type には
scatter
を指定します。末尾のseries変数がプロットされている座標の情報が格納されているオブジェクトです。
Highcharts.chart('container', {
chart: {
type: 'scatter',
zooming: {
type: 'xy'
}
},
...略...
series
});
実行結果
上記のHTMLファイルをWebブラウザで表示します。下図のページが表示されます。
散布図が描画できました。
マウスポインタをドットに重ねると重なった位置のプロットのドット情報が吹き出しで表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用