Skip to content

Instantly share code, notes, and snippets.

@abierbaum
Created July 10, 2012 15:43
Show Gist options
  • Save abierbaum/3084208 to your computer and use it in GitHub Desktop.
Save abierbaum/3084208 to your computer and use it in GitHub Desktop.
Test for line chart in d3.js
var data = [3,7,9,1,4,6,8,2,5],
w = 700,
h = 300,
max_val = d3.max(data);
// Scales
x = d3.scale.linear()
.domain([0, data.length - 1])
.range([0, w]);
y = d3.scale.linear()
.domain([0, max_val])
.range([h, 0]);
// Base vis layer
var chart_svg = d3.select('body')
.append('svg:svg')
.attr('width', w)
.attr('height', h)
var line = d3.svg.line()
.x(function(d, i) { return x(i); })
.y(function(d, i) { return y(d); })
.interpolate('monotone');
// Add path layer
chart_svg.selectAll('path.line')
.data([data])
.enter().append('svg:path')
.attr("d", line);
// add circles
chart_svg.selectAll('circle')
.data(data)
.enter().append('svg:circle')
.attr('cx', function(d, i) { return x(i); })
.attr('cy', function(d, i) { return y(d); })
.attr('r', 10);
// Bar chart of the same data
var chart = d3.select('body').append('svg')
.attr('class', 'chart')
.attr('width', w)
.attr('height', 20 * data.length);
var x2 = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0,w]);
chart.selectAll('rect')
.data(data)
.enter().append('rect')
.attr('y', function(d, i) { return i * 20; })
.attr('width', x2)
.attr('height', 20);
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?1.27.2"></script>
<style type="text/css">
path {
fill: none;
stroke: #000;
stroke-width: 7px;
}
circle {
fill: #ccc;
stroke: #777;
stroke-width: 1px;
}
.chart rect {
stroke: white;
fill: steelblue;
}
</style>
</head>
<body>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment