Plotly メモ2019年12月14日 | |
はじめにJavaScript でグラフを描画する Plotly についてのメモ。 ベース以下のような HTML ファイルを用意する。 plot.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<title>plot</title>
</head>
<body>
<div id="plot"></div>
<script src="data.js"></script>
<script>
ここにコードを書く
</script>
</body>
</html>
ここでは、data.js にデータを書き込むことを想定している。 散布図data.js
const data1 = {
x: [0, 0.5, 1],
y: [0, 0.3, 0.5],
};
const data2 = {
x: [0, 0.5, 1],
y: [1, 0.4, 0.2],
};
コード
data1.name = "data1";
data1.mode = "lines+markers";
data1.type = "scatter";
data2.name = "data2";
data2.mode = "markers";
data2.type = "scatter";
const plot_data = [data1, data2];
Plotly.newPlot("plot", plot_data);
データの属性 type で "scatter" を指定する。属性 mode で "lines" を指定すると線を、"markers" を指定するとマーカーを、"lines+markers" を指定するとその両方を表示する。Plotly.newPlot() で描画している。第 1 引数は div 要素の id 名である。 レイアウトレイアウトで細かい表示の仕方を指定できる。たとえば、グラフのサイズを指定するには、次のようにする。
const layout = {
width: 640,
height: 480,
};
Plotly.newPlot("plot", plot_data, layout);
軸のタイトル
const layout = {
xaxis: { title: "X [m]" },
yaxis: { title: "Temperature [K]" },
};
タイトルと数字が重なってしまう場合は、automargin を有効にするとよいかもしれない。
yaxis: { title: "Temperature [K]", automargin: true },
値の範囲
const layout = {
xaxis: { range: [0, 1] },
yaxis: { range: [0, 1] },
};
軸の数字の書式の指定
yaxis: { title: "Temperature [K]", tickformat: ".3f" },
マージンの指定
margin: { l: 50, r: 50, b: 100, t: 100 },
コンター表示data.js
const n = 50;
let data_x = new Array(n*n);
let data_y = new Array(n*n);
let data_z = new Array(n*n);
l = 10.
x0 = -l*0.5;
y0 = -l*0.5;
dx = l/n;
dy = l/n;
for(let i = 0; i < n; i++) {
for(let j = 0; j < n; j++) {
x = x0 + i*dx;
y = y0 + j*dy;
z = Math.sin(x)*Math.cos(y);
data_x[i + j*n] = x;
data_y[i + j*n] = y;
data_z[i + j*n] = z;
}
}
コード
const plot_data = [{
x: data_x,
y: data_y,
z: data_z,
type: "contour",
colorscale: "Jet",
contours: {
coloring: "heatmap"
},
colorbar: { title: "z" }
}];
const plot_layout = {
xaxis: { title: 'x' },
yaxis: { title: 'y' },
width: 640,
height: 480,
margin: { l: 50, r: 50, b: 100, t: 100 },
};
Plotly.newPlot("plot", plot_data, plot_layout);
値の範囲コンターの値の範囲の指定は、データのほうで行う。
const plot_data = [{
contours: {
start: 0,
end: 1,
size: 0.1
},
}];
| |
| PENGUINITIS | |