D3

by jcinteractive

HTML

<script src="https://github.com/mbostock/d3/raw/v1.17.0/d3.js"></script>
<script src="https://github.com/mbostock/d3/raw/v1.17.0/d3.layout.js"></script>

CSS

body {
    width: 500px;
    margin: 100px auto;
}

rect {
    fill: #c2c2c2;
    stroke: #fff;
    shape-rendering: crispEdges;
    -webkit-transition: fill 0.3s;
    -moz-transition: fill 0.3s;
    -o-transition: fill 0.3s;
    -ms-transition: fill 0.3s;
    transition: fill 0.3s;
}
rect:hover {
    fill: #777;
}
line {
    stroke: #ccc;
    shape-rendering: crispEdges;
}
text {
    fill: #666;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

JavaScript

// A jQuery plugin which creates histograms using d3.js
(function( $ ) {
    $.d3charts = $.d3charts || {
        histogram: function(object, settings) {
            $(object).histogram(settings);
        },
        defaults: {
            data: [],
            width: null, // uses the width of the containing element
            height: null, // uses the height of the containing element
            bins: 10,
            bottompad: 10, // pixels of room to leave at the bottom for binlabels
            labelsize: null, // uses the height of the padding - 2 for font size
    
            // function which generates bin labels
            // by default it labels the bins from 1 to N, where N is the number of bins
            labelGenerator: function(d, i) { return i+1+""; }
        }
    };
    
    $.fn.extend({
        histogram: function(options) {
        var settings = jQuery.extend({}, $.d3charts.defaults, options);
            
        return this.each(function() {
            var $this = $(this);
            var w = settings.width === null ? $this.width() : settings.width;
            var h = settings.height === null ? $this.height() : settings.height;
            var ls = settings.labelsize === null ? settings.bottompad - 2 : settings.labelsize;
            
            d3.select(this).each(function(d, i) {

                var histogram = d3.layout.histogram().bins(settings.bins)
                    (settings.data);
                
                var x = d3.scale.ordinal()
                    .domain(histogram.map(function(d) { return d.x; }))
                    .rangeRoundBands([0, w]);
                 
                var y = d3.scale.linear()
                    .domain([0, d3.max(histogram, function(d) { return d.y; })])
                    .range([0, h - settings.bottompad]);
                
                var vis = d3.select(this).append("svg:svg")
                    .attr("class", "chart")
                    .attr("width", w)
                ...