1つの折れ線グラフを描く。
test9.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://d3js.org/d3.v4.js"></script>
</head>
<body>
<svg width="960" height="500"></svg>
</body>
<!-- 上記のsvg要素をJavaScript内で読み込むので、bodyより下にスクリプトのソースを定義する -->
<script src="./test9.js"></script>
</html>
test9.js
var svg = d3.select("svg"),
margin = {top: 20, right: 80, bottom: 30, left: 50},
width = svg.attr("width") - margin.left - margin.right,
height = svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// データ
var tokyo = [
{"month": 1, "temperature": 5.1},
{"month": 2, "temperature": 7.0},
{"month": 3, "temperature": 8.1},
{"month": 4, "temperature": 14.5},
{"month": 5, "temperature": 18.5},
{"month": 6, "temperature": 22.8},
{"month": 7, "temperature": 27.3},
{"month": 8, "temperature": 27.5},
{"month": 9, "temperature": 25.1},
{"month": 10, "temperature": 19.5},
{"month": 11, "temperature": 14.9},
{"month": 12, "temperature": 7.5},
];
var line = d3.line()
.x(function(d) {
console.log(d.month);
console.log(x(d.month));
return x(d.month); })
.y(function(d) {
console.log(d.temperature);
console.log(y(d.temperature));
return y(d.temperature); });
// X, Yの範囲を座標に置き換える
var x = d3.scaleLinear()
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
// Xの範囲はmonthの最小値から最大値
x.domain(d3.extent(tokyo, function(d) { return d.month; }));
// Yの範囲0からtemperatureの最大値
y.domain([0, d3.max(tokyo, function(d) { return d.temperature; })]);
// line chartを描く
g.append("path")
.attr("d", line(tokyo))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
// X軸
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Y軸
g.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("fill", "#000")
.text("Temperature (℃)");
実行例 (fc2に置いてあるテストページに飛びます)
0 件のコメント:
コメントを投稿