D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
d-keener
Full window
Github gist
drew block
Built with
blockbuilder.org
<!DOCTYPE html> <meta charset="utf-8"> <style> .bar { fill: steelblue; } .bar:hover { fill: lightblue; } .axis text { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none; } .tooltip { position: absolute; padding: 10px; font: 12px sans-serif; background: #222; color: #fff; border: 0px; border-radius: 8px; pointer-events: none; opacity: 0.9; visibility: hidden; } </style> <script src="//d3js.org/d3.v3.min.js"></script> <script> /////////////////////// // Parse the Data d3.csv("data.csv", function(data) { /////////////////////// // Chart Size Setup var margin = { top: 35, right: 0, bottom: 30, left: 40 }; var width = 960 - margin.left - margin.right; var height = 500 - margin.top - margin.bottom; var chart = d3.select(".chart") .attr("width", 960) .attr("height", 500) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); /////////////////////// // Scales var x = d3.scale.ordinal() .domain(data.map(function(d) { return d['state']; })) .rangeRoundBands([0, width], .1); var y = d3.scale.linear() .domain([0, d3.max(data, function(d) { return parseFloat(d['sq-miles']); }) * 1.1]) .range([height, 0]); /////////////////////// // Axis var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); chart.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); chart.append("g") .attr("class", "y axis") .call(yAxis); /////////////////////// // Title chart.append("text") .text('Bar Chart!') .attr("text-anchor", "middle") .attr("class", "graph-title") .attr("y", -10) .attr("x", width / 2.0); /////////////////////// // Bars var bar = chart.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d['state']); }) .attr("y", height) .attr("width", x.rangeBand()) .attr("height", 0); bar.transition() .duration(1500) .ease("elastic") .attr("y", function(d) { return y(parseFloat(d['sq-miles'])); }) .attr("height", function(d) { return height - y(parseFloat(d['sq-miles'])); }) /////////////////////// // Tooltips var tooltip = d3.select("body").append("div") .attr("class", "tooltip"); bar.on("mouseover", function(d) { tooltip.html(d['sq-miles']) .style("visibility", "visible"); }) .on("mousemove", function(d) { tooltip.style("top", event.pageY - (tooltip[0][0].clientHeight + 5) + "px") .style("left", event.pageX - (tooltip[0][0].clientWidth / 2.0) + "px"); }) .on("mouseout", function(d) { tooltip.style("visibility", "hidden"); }); }); </script> <body> <svg class="chart"></svg> </body>
https://d3js.org/d3.v3.min.js