d3.js で折れ線グラフを描画する方法のメモ。
<html> <head> <meta http-equiv="Content-Type" content="text/html;utf-8"> <title>graph</title> </head> <body> <div id="graph"></div> <script type="text/javascript" src="../d3.min.js"></script> <script type="text/javascript"> const org_dataset = [ ['01/01', 4], ['01/02', 5], ['01/03', 8], ['01/04', 10], ['01/05', 9], ['01/06', 12], ['01/07', 8], ['01/08', 7], ['01/09', 6], ['01/10', 8], ]; const dataset = []; for (let i = 0; i < org_dataset.length; i++) { let d = org_dataset[i]; dataset.push({date: d[0], x: i, y: d[1]}); } const width = 600; const height = 400; const margin = { "top": 40, "bottom": 40, "right": 40, "left": 40 }; const svg = d3.select("body") .append("svg") .attr("width", margin.left+width+margin.right) .attr("height", margin.top+height+margin.bottom) ; var xScale = d3.scaleLinear() .domain([0, d3.max(dataset, function(d) { return d.x; })]) .range([margin.left, margin.left+width]) ; var yScale = d3.scaleLinear() .domain([0, d3.max(dataset, function(d) { return d.y; })]) .range([margin.top+height, margin.top]) ; var xAxis = d3.axisBottom(xScale) .ticks(5) .tickFormat((d) => { return dataset[d].date; }) ; var yAxis = d3.axisLeft(yScale) .ticks(5); svg.append("g") .attr("transform", "translate(" + [0, margin.top+height].join(",") + ")") .call(xAxis) .append("text") .attr("fill", "black") .attr("x", (margin.left+width+margin.right)/2) .attr("y", margin.bottom/2) .attr("text-anchor", "middle") .attr("font-size", "10pt") .text("日付"); svg.append("g") .attr("transform", "translate(" + [margin.left, 0].join(",") + ")") .call(yAxis) .append("text") .attr("fill", "black") .attr("text-anchor", "middle") .attr("x", -(height+margin.top+margin.bottom)/2) .attr("y", -margin.left/2) .attr("transform", "rotate(-90)") .attr("font-size", "10pt") .text("値"); svg.append("path") .datum(dataset) .attr("fill", "none") .attr("stroke", "steelblue") .attr("stroke-width", 1.5) .attr("d", d3.line() .x(function(d) { return xScale(d.x); }) .y(function(d) { return yScale(d.y); }) ); </script> </body> </html>