var width = 500; var height = 300; var maxValue = d3.select('#maximum') .node() .value; var margin = { top: 20, left: 30, right: 30, bottom: 30 }; var svg = d3.select("#vis") .append("svg") .attr('width', width) .attr('height', height) .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); width = width - margin.left - margin.right; height = height - margin.top - margin.bottom; var yscale = d3.scaleLinear() .range([height, 0]) .domain([0, maxValue]); var xscale = d3.scaleBand() .range([0, width]) .padding(0.1); var xaxis = d3.axisBottom() .scale(xscale); var yaxis = d3.axisLeft() .scale(yscale); svg.append('g') .attr('transform', 'translate(0, ' + (height) + ')') .attr('class', 'x axis'); svg.append('g') .attr('class', 'y axis'); function update() { maxValue = d3.select('#maximum') .node() .value; var exampleData = createRandomData(maxValue); xscale.domain(d3.range(exampleData.length)); yscale.domain([0, maxValue]); var bars = svg.selectAll(".bar") .data(exampleData); bars .exit() .transition() .attr('height', 0) .attr('y', height) .remove(); var new_bars = bars .enter() .append('rect') .attr('class', 'bar') .attr("fill", "red") .attr('height', 0) .attr('y', height); new_bars.merge(bars) .transition() .attr("height", function(d, i) { return height - yscale(d); }) .attr("y", function(d, i) { return yscale(d); }) .attr("width", xscale.bandwidth()) .attr("x", function(d, i) { return xscale(i); }) var labels = svg.selectAll('.label') .data(exampleData); labels .exit() .transition() .attr('y', height) .attr('opacity', 0) .remove(); var new_labels = labels .enter() .append('text') .attr('class', 'label') .attr('opacity', 0) .attr('text-anchor', 'middle') .attr('y', height); new_labels.merge(labels) .transition() .attr('opacity', 1) .attr('x', function(d, i) { return xscale(i) + xscale.bandwidth() / 2; }) .attr('y', function(d) { return yscale(d) - 2; }) .text(function(d) { return d; }); svg.select('.x.axis') .transition() .call(xaxis); svg.select('.y.axis') .transition() .call(yaxis); } function createRandomData(maxValue) { var numDataItems = Math.floor((Math.random() * 30) + 1); var d = []; for (var i = 0; i < numDataItems; i++) { d.push(Math.floor((Math.random() * maxValue) + 1)); } return d; } update();