D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jpmarindiaz
Full window
Github gist
simple d3 barchart
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0; position:fixed; top:0;right:0;bottom:0;left:0; } .bars { fill: #ff28b4; } text.label { text-anchor: middle; font-size: 0.8em; fill: #9954aa; font-family: "monospace"; } </style> </head> <body> <script> // Feel free to change or delete any of the code you see in this editor! var svg = d3.select("body").append("svg") .attr("width", 960) .attr("height", 500) .attr('transform', 'translate(50,50)') // svg.append("text") // .text("Edit the code below to change me!") // .attr("y", 200) // .attr("x", 120) // .attr("font-size", 36) // .attr("font-family", "monospace"); var height = 300; var width = 400; // data var data = [ {key: "a", value: 20}, {key: "b", value: 30}, {key: "c", value: 550}, {key: "d", value: 200}, {key: "e", value: 50} ]; var yMax = d3.max(data, function(d){return d.value}); console.log(yMax) var y = d3.scaleLinear() .domain([0, yMax *1.15]) .range([height, 0]); var xValues = data.map(function(d){ return d.key }); console.log(xValues); var x = d3.scaleBand() .domain(xValues) .rangeRound([0, width]) .paddingInner(0.2) .paddingOuter(0.2); svg .append('g') .selectAll('.bars') .data(data) .enter() .append('rect') .attr('class','bars') .attr('height', function(d){ return height - y(d.value) }) .attr('width', x.bandwidth()) .attr('x', function(d){return x(d.key)}) .attr('y', function(d){ return y(d.value) }); //.attr('color', '#000088') var xAxis = d3.axisBottom() .scale(x); svg.append('g') .attr('transform', 'translate(0,' + height + ')') .call(xAxis) var yAxis = d3.axisRight() .scale(y); svg.append('g') .attr('transform', 'translate(5,0)') .call(yAxis) svg .selectAll(".label") .data(data) .enter() .append('text') .attr('class', 'label') .attr('dx', function(d) { return x(d.key) + x.bandwidth()/2 }) .attr('dy', function(d) {return y(d.value) - 5}) .text(function(d){ return d.value}) </script> </body>
https://d3js.org/d3.v4.min.js