Created
December 1, 2017 21:04
-
-
Save mhkeller/ca17b221c0c02413f17b91c14dfc402c to your computer and use it in GitHub Desktop.
Responsive D3 chart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
path { | |
fill: none; | |
stroke: #000; | |
stroke-width: 10px; | |
} | |
#container{ | |
width: 100%; | |
max-width: 900px; | |
height: 300px; | |
background-color: #0fc; | |
} | |
</style> | |
<body> | |
<script src="//d3js.org/d3.v4.min.js"></script> | |
<script> | |
var container | |
var svg | |
var g | |
var linePath | |
var xScale = d3.scaleLinear() | |
var yScale = d3.scaleLinear() | |
var xExtent | |
var yExtent | |
var width | |
var height | |
var line = d3.line() | |
.x(function (d) { | |
return xScale(d.key) | |
}) | |
.y(function (d) { | |
return yScale(d.value) | |
}) | |
var chartData | |
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}] | |
function bakeChart () { | |
container = d3.select('body') | |
.append("div") | |
.attr('id', 'container') | |
svg = container | |
.append("svg") | |
g = svg | |
.append('g') | |
linePath = g | |
.append('path') | |
.classed('line', true) | |
.datum(chartData) | |
} | |
function setValues () { | |
var bbox = container.node().getBoundingClientRect() | |
yExtent = d3.extent(chartData, function (d) { | |
return d.value | |
}) | |
xExtent = d3.extent(chartData, function (d) { | |
return d.key | |
}) | |
width = bbox.width | |
height = bbox.height | |
xScale.domain(xExtent) | |
.range([0, width]) | |
yScale.domain(yExtent) | |
.range([height, 0]) | |
} | |
function renderChart () { | |
svg.attr("width", width) | |
.attr("height", height) | |
linePath | |
.attr('d', line) | |
} | |
function onResize () { | |
setValues(chartData) | |
renderChart(chartData) | |
} | |
loadData('my/data.json', function (d) { | |
chartData = d | |
bakeChart() | |
setValues() | |
renderChart() | |
}) | |
window.addEventListener('resize', onResize) | |
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