Skip to content

Instantly share code, notes, and snippets.

@mhkeller
Created December 1, 2017 00:28
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 mhkeller/7d2869752cfd041b5bdcdc23d7aa6c25 to your computer and use it in GitHub Desktop.
Save mhkeller/7d2869752cfd041b5bdcdc23d7aa6c25 to your computer and use it in GitHub Desktop.
Basic D3 Line Chart
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
fill: none;
stroke: #000;
stroke-width: 10px;
}
#container{
width: 900px;
height: 300px;
background-color: #f0c;
}
</style>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var width = 900
var height = 300
var container = d3.select('body')
.append("div")
.attr('id', 'container')
var svg = container
.append("svg")
.attr('width', width)
.attr('height', height)
var xScale = d3.scaleLinear()
.range([0, width])
var yScale = d3.scaleLinear()
.range([height, 0])
var g = svg.append("g")
var data = [{"key":0,"value":1},{"key":1,"value":5},{"key":2,"value":10},{"key":3,"value":15},{"key":4,"value":20},{"key":5,"value":25},{"key":6,"value":30},{"key":7,"value":35},{"key":8,"value":40},{"key":9,"value":45},{"key":10,"value":49},{"key":11,"value":91},{"key":12,"value":88},{"key":13,"value":70},{"key":14,"value":93}]
loadData('my/data.json', function (data) {
svg.attr("width", width)
.attr("height", height)
var yExtent = d3.extent(data, function (d) {
return d.value
})
var xExtent = d3.extent(data, function (d) {
return d.key
})
yScale.domain(yExtent)
xScale.domain(xExtent)
var line = d3.line()
.x(function (d) { return xScale(d.key) })
.y(function (d) { return yScale(d.value) })
g.append('path')
.classed('line', true)
.datum(data)
.attr('d', line)
})
function loadData (str, cb) {
cb(data)
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment