D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
smckissock
Full window
Github gist
Horizontal Bars
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Week 3</title> <script type="text/javascript" src="https://d3js.org/d3.v3.js"></script> <style type="text/css"> h1 { font-family: sans-serif; color: Black; font-size: 28px; } </style> </head> <body> <h1>United States Government Outlays - <span name="year"></span></h1> <form> Choose year: <select class="select" /> </form> <script type="text/javascript"> d3.csv("OutlaysByAgency1962_2020.csv", function (data) { console.log(data); var years = []; // It would be better to just read the fields.. for (i = 1962; i < 2021; i++) { if (i < 2015) years.push(i); else years.push(i + " estimate"); } var select = d3.select('select').on('change', changeYear); d3.select('select') .selectAll('option') .data(years) .enter() .append('option') .text(function (d) { return d; }) .attr("value", (function (d, i) { return i; })); select.property("value", '52'); drawChart(years[52]); function drawChart(year) { addCommas = d3.format(",d"); d3.select("span").text(year); // Sort descending on selected year data.sort(function (a, b) { return +b[year] - +a[year]; }); d3.select("svg").remove(); var svg = d3.select("body") .append("svg") .attr("width", 1000) .attr("height", 800); svg.selectAll("rect") .data(data) .enter() .append("rect") .attr("x", 0) .attr("width", function (d) { var num = +d[year]; if (num < 0) return 0; else return num / 1000; }) .attr("y", function (d, i) { return i * 24; }) .attr("height", 20) .style("fill", "lightgreen"); svg.selectAll("text") .data(data) .enter() .append("text") .text(function (d) { var dollars = +d[year] * 1000000 return d['Department or other unit'] + ' $' + addCommas(dollars); }) .attr('x', 6) .attr('y', function (d, i) { return (i * 24) - 8; }) .attr('font-family', 'sans-serif') .attr('font-size', '14px'); } function changeYear() { var yearIndex = d3.select('select').property('value'); drawChart(years[yearIndex]); }; }); </script> </body> </html>
Modified
http://d3js.org/d3.v3.js
to a secure url
https://d3js.org/d3.v3.js