Skip to content

Instantly share code, notes, and snippets.

@vwochnik
Forked from katsumitakano/index.html
Last active June 13, 2016 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vwochnik/2eb0efc299ae49d2a25f to your computer and use it in GitHub Desktop.
Save vwochnik/2eb0efc299ae49d2a25f to your computer and use it in GitHub Desktop.
Line Chart with Grid [D3]
license: mit
var margin = {top: 20, right: 100, bottom: 30, left: 100},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var dataset = [
{x: 0, y: 15},
{x: 2, y: 3},
{x: 4, y: 35},
{x: 6, y: 2},
{x: 8, y: 38},
{x: 10, y: 40}
];
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d){ return d.x; })])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d){ return d.y; })])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.innerTickSize(-height)
.outerTickSize(0)
.tickPadding(10);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.innerTickSize(-width)
.outerTickSize(0)
.tickPadding(10);
var line = d3.svg.line()
.x(function(d) { return xScale(d.x); })
.y(function(d) { return yScale(d.y); })
.interpolate(function(pts) {
var res = ""+pts[0];
for (var i = 0; i < pts.length - 1; i++) {
var s = 1 / (pts[i+1][0] - pts[i][0]) / 5;
for (var t = s; t <= 1.0; t += s) {
var r = Math.max(0, Math.min(1, Math.abs((pts[i+1][1] - pts[i][1]) / (pts[i+1][0] - pts[i][0])))),
c = t*(1-r) + (1 - Math.cos(t*Math.PI)) / 2 * r;
res += "L" + [(1-t)*pts[i][0]+t*pts[i+1][0], pts[i][1]*(1-c) + pts[i+1][1]*c];
}
}
return res;
});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
svg.append("path")
.data([dataset])
.attr("class", "line")
.attr("d", line);
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Line Chart</title>
<style>
.axis path,
.axis line{
fill: none;
stroke: black;
}
.line{
fill: none;
stroke: blue;
stroke-width: 2px;
}
.tick text{
font-size: 12px;
}
.tick line{
opacity: 0.2;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script src="draw.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment