D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jalapic
Full window
Github gist
Horizontal Bar with scale and axes
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> <title>horizontal bar</title> <style type="text/css"> h1{ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 26px; font-style: bold; } body { background-color: #F9FFFF; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; font-style: bold; } svg { background-color: #F9FFFF; } .myrect { fill: #191970; } .myrect:hover { fill: #af1e23; } .axis path, .axis line { fill: none; stroke: black; shape-rendering: crispEdges; } .axis text { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-style: bold; font-size: 11px; } .y.axis path, .y.axis line { opacity: 0; } </style> <h1>Stop and Frisk Totals by Race for NYC in 2014 </h1> </head> <body> <p>Original data available at <a href="https://www.nyc.gov/html/nypd/html/analysis_and_planning/stop_question_and_frisk_report.shtml">NYC.gov</a>.</p> <script type="text/javascript"> var w = 800; var h = 200; var padding = [ 20, 20, 30, 210 ]; //Top, right, bottom, left // scale x data linearly var widthScale = d3.scale.linear() .range([ 0, w - padding[1] - padding[3] ]); // scale y data ordinally var heightScale = d3.scale.ordinal() .rangeRoundBands([ padding[0], h - padding[2] ], 0.1); // add x-axis var xAxis = d3.svg.axis() .scale(widthScale) .orient("bottom") // .tickFormat(d3.format("d")); //remove comma ; // add y-axis var yAxis = d3.svg.axis() .scale(heightScale) .orient("left"); var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); d3.csv("stopfrisksum.txt", function(data) { data.sort(function(a, b) { return d3.descending(+a.total, +b.total); }); // inform domain to widthScale - x data widthScale.domain([ 0, d3.max(data, function(d) { return +d.total; }) ]) .nice(); // inform domain to heightScale - y axis heightScale.domain(data.map(function(d) { return d.race; } )); var rects = svg.selectAll("rect") .data(data) .enter() .append("rect"); rects.attr("class", "myrect") .attr("x", padding[3]) .attr("y", function(d) { return heightScale(d.race); }) .attr("width", function(d) { return widthScale(d.total); }) .attr("height", heightScale.rangeBand()) //.attr("height", 15) .append("title") .text(function(d) { return d.race + " individuals were stopped and frisked " + d.total + " times in NYC in 2014"; }); // add x-axis svg.append("g") .attr("class", "x axis") .attr("transform", "translate(" + padding[3] + "," + (h - padding[2]) + ")") .call(xAxis); // add y-axis svg.append("g") .attr("class", "y axis") .attr("transform", "translate(" + padding[3] + ",0)") .call(yAxis); }); </script> </body> </html>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js