Skip to content

Instantly share code, notes, and snippets.

@mathfur
Last active January 31, 2021 14:08
Show Gist options
  • Save mathfur/5845179 to your computer and use it in GitHub Desktop.
Save mathfur/5845179 to your computer and use it in GitHub Desktop.
foo.csvを用意してブラウザで開くと、折れ線グラフが表示できる。 (foo.csvは1列で構成。1行目がvalueヘッダ、2行目以降に数値を並べたもの。)
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
line {
stroke: black;
}
text {
font-family: Arial;
font-size: 9pt;
}
</style>
<body>
<script>
var margin = {top: 40, right: 10, bottom: 10, left: 10},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
var base = svg.append("g")
.attr("transform", "translate(" + margin.left + ", " + margin.top + ")");
// foo.csvは1列のみ("value"ヘッダ付き)
// 1列目に数値を並べておく
d3.csv("foo.csv", function(error, csv){
var data = csv.map(function(d){ return d.value })
var width = 400,
height = 200,
margin = 20;
yScale = d3.scale.linear().domain([0, d3.max(data)]).range([margin, height - margin]),
xScale = d3.scale.linear().domain([0, data.length]).range([margin, width - margin])
var line = d3.svg.line()
.x(function(d,i) { return xScale(i); })
.y(function(d,i) { return yScale(d); });
base.append("path")
.attr("d", line(data));
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("top")
.ticks(5)
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5)
base.append("g")
.attr("class", "axis")
.attr("transform", "translate(0, " + margin + ")")
.call(xAxis);
base.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + margin + ", 0)")
.call(yAxis);
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment