<fieldset> <input type="text" name="width" placeholder="width"> <input type="text" name="height" placeholder="height"> <input type="text" name="data" placeholder="data e.g. 10,40,20"> </fieldset> <svg id="chart" style='width:600px; height:600px;'></svg>
function BarChart(svg) { var svg = d3.select(svg); var barContainer = svg.append("g"); var labelContainer = svg.append("g"); this.height = $R.state(200); this.width = $R.state(200); this.data = $R.state([]); var y = $R(BarChart.y, this) .bindTo(this.height, this.data); var x = $R(BarChart.x, this) .bindTo(this.width, this.data); var bars = $R(BarChart.bars, this) .bindTo(barContainer, this.data, this.height, x, y); var labels = $R(BarChart.labels, this) .bindTo(labelContainer, this.data, x, y); } BarChart.x = function (width, data) { return d3.scale.ordinal() .domain(d3.range(0, data.length)) .rangeRoundBands([0, width], .1); } BarChart.y = function (height, data) { return d3.scale.linear() .domain([0, d3.max(data, function(d) { return d.value })]) .range([height, 0]); } BarChart.bars = function (barContainer, data, height, x, y) { var bars = barContainer.selectAll(".bar").data(data); bars.enter().append("rect") .attr("class", "bar"); bars.attr("x", function(d, i) { return x(i); }) .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.value); }) .attr("height", function(d) { return height - y(d.value); }); bars.exit().remove() } BarChart.labels = function (labelContainer, data, x, y) { var labels = labelContainer.selectAll(".label").data(data); labels.enter().append("text") .attr("class", "label"); labels.attr("x", function(d, i) { return x(i) + x.rangeBand() / 2 - 8; }) .text(function (d,i) { return d.name; }) .attr("y", function(d) { return y(d.value) + 10; }) labels.exit().remove() } var chart = new BarChart(document.getElementById("chart")); chart.data([{name:"Foo", value:10}, {name:"Bar", value:20}, {name:"Baz", value:60}]); $("input[name=width]").on("change", function () { chart.width(parseInt(this.value)); }); $("input[name=height]").on("change", function () { chart.height(parseInt(this.value)); }); $("input[name=data]").on("change", function () { var data = this.value .split(',') .map(function(d, i){ return {name:"#"+(i+1), value:parseInt(d)} }); chart.data(data); });
.bar {fill: #1D8300;} .label {fill: #FFF; font-size:10px; font-family:sans-serif;} fieldset {margin-bottom:20px}