Resize an d3 svg chart with the width of the window
A Pen by Dave Staab on CodePen.
Resize an d3 svg chart with the width of the window
A Pen by Dave Staab on CodePen.
| <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> | |
| <h1>Resize the window to see the svg chart resize to 100% width.</h1> |
| var height = 100; | |
| var svg = d3 | |
| .select('body') | |
| .append('svg') | |
| .attr("width", "100%") | |
| .attr("height", height) | |
| .append("g"); | |
| var padding = 50; | |
| var parseDate = d3.time.format("%m %Y").parse; | |
| var x = d3.time.scale().range([padding, getWidth() - padding*2]); | |
| var xAxis = d3.svg.axis().scale(x).orient("bottom"); | |
| xAxisElem = svg.append("g") | |
| .attr("class", "x axis") | |
| .attr("transform", "translate(0," + (height - padding) + ")") | |
| .call(xAxis); | |
| function getWidth(){ | |
| var width = d3.select("body").node().offsetWidth; | |
| console.log("width", width); | |
| return width; | |
| }; | |
| window.onresize = function() { | |
| var width = getWidth(); | |
| update(data, width); | |
| }; | |
| function update(data, width) { | |
| x.range([padding, width - padding*2]) | |
| .domain(d3.extent(data.months, function(d) { return d.date; })); | |
| xAxisElem.transition().call(xAxis); | |
| } | |
| //update(data, getWidth()); | |
| // data | |
| var data = { | |
| tpc: 2300000, | |
| funded: 370000, | |
| months: [ | |
| crt('01 2015', 0, 0, 0, 0), | |
| crt('02 2015', 10000, 9000, 8000, 7000), | |
| crt('03 2015', 20000, 21000, 19000, 15000), | |
| crt('04 2015', 30000, 27000, 25000, 20000), | |
| crt('05 2015', 40000, 41000, 39000, 33000), | |
| crt('06 2015', 50000, 49000, 47000, 40000), | |
| crt('07 2015', 60000, 60000, 58000, 42000), | |
| crt('08 2015', 70000, null, null, null), | |
| crt('09 2015', 80000, null, null, null), | |
| crt('10 2015', 90000, null, null, null), | |
| crt('11 2015', 100000, null, null, null), | |
| crt('12 2015', 110000, null, null, null) | |
| ] | |
| }; | |
| // create function | |
| function crt(date, planned, work, actual, commitment){ | |
| return { | |
| date: parseDate(date), | |
| planned: planned, | |
| work: work, | |
| actual: actual, | |
| commitment: commitment | |
| }; | |
| } |
| <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script> | |
| <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> |
| svg { | |
| background-color: #EEEEEE; | |
| } | |
| .axis .domain { | |
| fill: none; | |
| stroke: black; | |
| stroke-color: black; | |
| } |