D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
VictorHom
Full window
Github gist
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; } .axis text { font-family: 'Open Sans', sans-serif; font-size: 21pt; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis text { font-size: 22pt; } </style> </head> <body> <script> var data = [ {country: "China", population: 1376048943}, {country: "India", population:1311050527}, {country: "USA", population: 321773631}, {country: "Indonesia", population: 257563815}, {country: "Brazil", population: 207847528} ]; var outerwidth = 960; var outerHeight =500 var margin = {left: 90, top: 25, right: 26, bottom: 49} var barPadding = 0.2; var innerWidth = outerWidth - margin.left - margin.right; var innerHeight = outerHeight - margin.top - margin.bottom; // Feel free to change or delete any of the code you see in this editor! var svg = d3.select("body").append("svg") .attr("width", outerWidth) .attr("height", outerHeight) var g = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var xAxisG = g.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + innerHeight + ")"); var yAxisG = g.append("g") .attr("class", "y axis"); var xScale = d3.scaleBand().range([0, innerWidth], barPadding) var yScale = d3.scaleLinear().range([innerHeight, 0]); // Use a modified SI formatter that uses "B" for Billion. var siFormat = d3.format("s"); var customTickFormat = function (d){ return siFormat(d).replace("G", "B"); }; var xAxis = d3.svg.axis().scale(xScale).orient("bottom") .outerTickSize(0); var yAxis = d3.svg.axis().scale(yScale).orient("left") .ticks(5) .tickFormat(customTickFormat) .outerTickSize(0); function render(data){ xScale.domain( data.map( function (d){ return d[xColumn]; })); yScale.domain([0, d3.max(data, function (d){ return d[yColumn]; })]); xAxisG.call(xAxis); yAxisG.call(yAxis); var bars = g.selectAll("rect").data(data); bars.enter().append("rect") .attr("width", xScale.rangeBand()); bars .attr("x", function (d){ return xScale(d[xColumn]); }) .attr("y", function (d){ return yScale(d[yColumn]); }) .attr("height", function (d){ return innerHeight - yScale(d[yColumn]); }); bars.exit().remove(); } function type(d){ d.population = +d.population; return d; } d3.json(data, type, render); </script> </body>
https://d3js.org/d3.v4.min.js