Built with blockbuilder.org
forked from cdagli's block: Clipped Bar Chart
| license: mit |
Built with blockbuilder.org
forked from cdagli's block: Clipped Bar Chart
| <!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: steelblue; | |
| opacity: .4; | |
| } | |
| .bar:hover { | |
| opacity: 1; | |
| } | |
| .bar text { | |
| fill: white; | |
| font: 16px sans-serif; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <script> | |
| 'use strict'; | |
| function generateData(firstValue, dataCount, bucketSize) | |
| { | |
| var data = []; | |
| for(var i = 0; i<dataCount; i++) | |
| { | |
| data.push({ | |
| start: firstValue + (i * bucketSize), | |
| count: Math.round(Math.random() * 500) | |
| }) | |
| } | |
| return data; | |
| } | |
| var data = generateData(200, 20, 100); | |
| console.log(data) | |
| 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 startArr = data.map(function(d){ return d.start}); | |
| var endArr = data.map(function(d){ return d.end}); | |
| var x = d3.scale.ordinal().rangeRoundBands([0, width]).domain(startArr.concat(endArr)); | |
| var yMinValue = d3.min(data.map(function(d){ return d.count})); | |
| var yMaxValue = d3.max(data.map(function(d){ return d.count})); | |
| var y = d3.scale.linear().range([0, height]).domain([yMinValue > 0 ? 0 : yMinValue, yMaxValue < 0 ? 0 : yMaxValue]) | |
| .range([height, 0]).nice(); | |
| 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) { console.log(x(d.start)); return x(d.start)}, | |
| width: x.rangeBand(), | |
| height: function (d) | |
| { | |
| return Math.abs(y(d.count) - y(0)); | |
| }, | |
| y: function (d) | |
| { | |
| return d.count > 0 ? y(d.count) : y(0); | |
| } | |
| }).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> |