D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
cdagli
Full window
Github gist
Clipped Bar Chart
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v3.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } .bar { fill: red; opacity: .4; } .bar:hover { opacity: 1; } .bar text { fill: white; font: 16px sans-serif; } </style> </head> <body> <script> var data = [ { start: 100, count: 3 }, { start: 200, count: 5 }, { start: 300, count: 10 }, { start: 500, count: 4 }, { start: 600, count: 2 }, ] var margin = {top: 20, right: 20, bottom: 20, left: 20}, padding = {top: 60, right: 60, bottom: 60, left: 60}, outerWidth = 960, outerHeight = 500, innerWidth = outerWidth - margin.left - margin.right, innerHeight = outerHeight - margin.top - margin.bottom, width = innerWidth - padding.left - padding.right, height = innerHeight - padding.top - padding.bottom; var svg = d3.select("body").append("svg") .attr("width", outerWidth) .attr("height", outerHeight) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var x = d3.scale.linear().domain([100, 600]).range([0, width]); var y = d3.scale.linear().domain([0, 10]).range([0, height]); var dataLine = [ { start: 0, count: 0 }, { start: 160, count: 3 }, { start: 320, count: 5 }, { start: 480, count: 10 }, { start: 480, count: 0 }, { start: 640, count: 0 }, { start: 640, count: 4 }, { start: 800, count: 2 }, { start: 960, count: 0 } ] var xLine = d3.scale.linear().domain([0, 800]).range([0, width]); var yLine = d3.scale.linear().domain([0, 10]).range([0, height]); var area = d3.svg.line() .x(function(d) { return xLine(d.start); }) .y(function(d) { return height - yLine(d.count); }) var animateLine = svg.append('clipPath') .attr('id', 'ellipse-clip') .append("path") .datum(dataLine) .attr("d", area) var barGroup = svg.append('g').attr("clip-path","url(#ellipse-clip)") var bar = barGroup.selectAll(".bar") .data(data) .enter().append("g") .attr("class", "bar") bar.append('rect').attr({ x: function(d) { return x(d.start)}, width: width / data.length, height: function(d) { return y(d.count)}, y: function(d) { return height - y(d.count)} }).attr('class', 'bar') bar.append("text") .attr("dy", ".75em") .attr("y", height - 20) .attr("x", function(d){return x(d.start) + 80 }) .attr("text-anchor", "middle") .text(function(d) { return d.count; }); </script> </body>
https://d3js.org/d3.v3.min.js