D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
BenHeubl
Full window
Github gist
responsive d3
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="w.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } svg { width:100%; height: 100% } text { font-family: sans-serif; font-size: 10px; } rect { fill: #ededed; } rect:hover { fill: #000000; } path { fill: none; stroke: #161616; } line { stroke: #000000; } </style> </head> <body> <svg width ="1000" heigth="350"> <g class="chart-wrapper" transform="translate(30,20)"> <g class="bars"></g> <g class="x axis"></g> <g class="y axis"> </g> </svg> <script> var maxWidth = 900, rightPadding = 70; var xScale, yScale, xAxisComponent, yAxisComponent; var numBars = 2, yMax = 100; var data = [55, 45], labels = ["Leave", "Remain"]; var container = d3.select('svg g.chart-wrapper'), barGroup = container.select('.bars') xAxis = container.select('.x.axis') yAxis = container.select('.y.axis'); function intToChar(i) { return labels[i]; } function randomData(data) { for(var i = 0; i < numBars; i++) data[i] = Math.random() * yMax; return data; } function initChart() { var width = 400, height = 300; data = randomData(data); // Initialise scales xScale = d3.scale.ordinal() .domain(data.map(function(d, i) {return intToChar(i);})) .rangeBands([0, width], 0.04); yScale = d3.scale.linear() .domain([0, yMax]) .range([height, 0]); // Build the x-axis xAxisComponent = d3.svg.axis() .scale(xScale) .orient('bottom'); xAxis.attr('transform', 'translate(0,'+height+')'); // Build the y-axis yAxisComponent = d3.svg.axis() .scale(yScale) .orient('left'); yAxis.call(yAxisComponent); } function initEvents() { // Set up event handler for resizes W.addListener(update); // Update data button d3.select('#update').on('click', function() { data = randomData(data); update(); }); } function update() { updateScales(); updateAxes(); updateBars(); } function updateScales() { var width = d3.min([W.getViewportWidth(), maxWidth]) - rightPadding; xScale.rangeBands([0, width], 0.04); } function updateAxes() { xAxis.transition().call(xAxisComponent); } function updateBars() { var u = barGroup .selectAll('rect') .data(data); u.enter() .append('rect') .classed("rectus", true); u.exit() .remove(); u.transition() .attr('x', function(d, i) {return xScale(intToChar(i));}) .attr('width', xScale.rangeBand()) .attr('y', function(d) {return yScale(d);}) .attr('height', function(d) {return yScale(0) - yScale(d);}); } initChart(); update(); initEvents(); </script> </body>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js