D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
lucamerzi
Full window
Github gist
bar chart with svg
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>D3 Bar Chart</title> <script src="https://d3js.org/d3.v5.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } #chart { width:800px;height:400px;background-color:#f7f7f7;margin:25px auto; } .bar { display:inline-block;width:25px;height:300px;background-color:#7ED26D;margin-right:5px; } </style> </head> <body> <div id="chart"></div> <script> // create variables for often-used values let chart_width = 800 let chart_height = 400 let bar_padding = 5 // generate random data var data = []; for (let i = 0; i < 25; i++){ // randomUniform returns a function, which has to be immediately called data.push(Math.floor(d3.randomUniform(1, 50)())) } // create svg element let svg = d3.select("#chart") .append("svg") .attr("width", chart_width) .attr("height", chart_height) // append rects in svg svg.selectAll("rect") .data(data) .enter() .append("rect") .attr("x", function(d,i){ return i * (chart_width / data.length) }) .attr("y", function(d){ return chart_height - d * 5 }) .attr("width", chart_width / data.length - bar_padding ) .attr("height", function(d){ return d * 5 }) .attr("fill", "#7ED26D") // create labels svg.selectAll("text") .data(data) .enter() .append("text") .text(function(d){ return d }) .attr("x", function(d, i){ return i * (chart_width / data.length) + (chart_width / data.length - bar_padding) / 2 }) .attr("y", function(d){ return chart_height - d * 5 + 15 }) .attr("font-size", 14) .attr("fill", "#fff") .attr("text-anchor", "middle") </script> </body>
https://d3js.org/d3.v5.min.js