D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
kheaney21
Full window
Github gist
Line
<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]); var line = d3.line() .x(function(d, i ) { return 20 * i; } ) .y(function(d) { return yScale(d.value) }); //create svg element var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); var xAxis = d3.axisBottom().scale(xScale).ticks(5); var yAxis = d3.axisLeft().scale(yScale).ticks(5); svg.selectAll("line") .data(dataset) .enter() .append("line") .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.append("path") .data(dataset) .attr("stroke", "blue") .attr("stroke-width", 1.5) .attr("d", line); //x axis svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + (h - padding) + ")") .call(xAxis); //y axis svg.append("g") .attr("class", "y axis") .attr("transform", "translate(" + padding + ", 0)") .call(yAxis); </script> </body> </html>
https://d3js.org/d3.v5.min.js