D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
kheaney21
Full window
Github gist
Bar Chart
<html lang = "en"> <head> <meta charset = "utf-8"> <title>Bar Chart</title> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> <script type = "text/javascript"> //width and height var w = 600; var h = 400; var padding = 15; var numBars = 5; var states = ["Alabama","Alaska","Arizona","Arkansas","California"]; /* var dataset; //load data d3.csv('weather.csv', function(d) { //data.forEach(function(d) { //dataset.push(d.precipitation); return { //max: d.Maximum, //min: d.Minimum, //month: d.Month, precipitation: d.Precipitation //speed: d.Speed, //state: d.State, //year: d.Year }; }, function(d) { dataset.push(d.precipitation); }); var temp; var string; for(var i = 0; i < numBars; i++) { string = dataset.get(i); state = states.get(i); temp = {state: string}; dataset.push(temp); }*/ //var dataset = data.slice(0, numBars + 1); dataset = [{state: "Alabama", value: 164.6}, {state: "Alaska", value: 973.2}, {state: "Arizona", value: 43.1}, {state: "Arkansas", value: 96}, {state: "California", value: 323.5}]; //scale function var xScale = d3.scaleBand() //.domain(["Alabama","Alaska","Arizona","Arkansas","California"]) .domain(d3.range(dataset.length)) //.range([padding, w-padding * 2]); .rangeRound([0, w]) .paddingInner(0.05); var yScale = d3.scaleLinear() .domain([0, d3.max(dataset, function(d) { return d.value; })]) //.range([padding, w-padding * 2]); .range([0, h - padding]); //create svg element var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", function(d, i) { return xScale(i); }) .attr("y", function(d) { return h - yScale(d.value); }) .attr("width", xScale.bandwidth()) .attr("height", function(d) { return yScale(d.value); }) .attr("fill", function(d) { return "rgb(0, " + (d.value * 0.5) + ", 50)"; }); svg.selectAll("text") .data(dataset) .enter() .append("text") .text(function(d) { return d.value; }) .attr("text-anchor", "middle") .attr("x", function(d, i) { return xScale(i) + padding;//, + xScale.bandwidth() / 2; }) .attr("y", function(d) { return h - yScale(d.value) + padding; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") .attr("fill", "white"); </script> </body> </html>
https://d3js.org/d3.v5.min.js