<style>@import 'https://fonts.googleapis.com/css?family=Sancreek';
.axis text,.bar text {fill:
font-size:90%; text-shadow:3px 3px 3px
</style><svg id='svg1' width='650' height='350'
style='background-color:lavender;'/><script>
var data=d3.range(3000).map(d3.randomBates(5)),
formatCount=d3.format(',.0f');
var svg=d3.select('#svg1'),
m=30,margin={top:m,right:m,bottom:m,left:m},
width=+svg.attr('width')-margin.left-margin.right,
height=+svg.attr('height')-margin.top-margin.bottom,
tr='translate('+margin.left+','+margin.top+')',
g=svg.append('g').attr('transform',tr);
var x=d3.scaleLinear().rangeRound([0,width]);
var bins=d3.histogram().domain(x.domain())
.thresholds(x.ticks(30))(data);
var y=d3.scaleLinear().range([height,0])
.domain([0,1.1*d3.max(bins,function(d){return d.length;})]);
var bar=g.selectAll('.bar').data(bins).enter()
.append('g').attr('class','bar')
.attr('transform',function(d){
return 'translate('+x(d.x0)+','+y(d.length)+')';});
bar.append('rect').attr('x',0)
.attr('width',x(bins[0].x1)-x(bins[0].x0)-2)
.attr('height',function(d){return height-y(d.length);});
bar.append('text').attr('text-anchor','middle')
.text(function(d){return formatCount(d.length);})
.attr('dy','.55em').attr('y',-10)
.attr('x',(x(bins[0].x1)-x(bins[0].x0))/2);
g.append('g').attr('class','axis axis--x')
.attr('transform','translate(0,'+height+')');
g.append('text').attr('y',5)
.attr('font-family','Sancreek')
.text('The Example of D3 Histograms');
No comments:
Post a Comment