score:30

Accepted answer

bar charts in dc.js use the xunits function to automatically calculate the width of the bars in a histogram based on the range of your x-axis. if you want to set the width to a static value you can use a custom xunits function for example:

chart.xunits(function(){return 10;});

this should give you a more fitting width.

score:4

the suggestion given by user2129903 to use the chart.xunits() to specify a custom xunits function is indeed the way to go. i'd like to add to that an example and a bit of an explanation as to choose the return value of that custom function.

the doc says:

this function is expected to return a javascript array of all data points on x axis, or the number of points on the axis.

that is, assuming you want to make a histogram, you can either directly specify the number of bins or calculate it from your desired bin size and return that from that function. you need to specify this when the numeric keys of your grouping are not successive, equidistant integers.

here is an example:

<!doctype html><meta charset="utf-8">
<head>
    <link rel="stylesheet" type="text/css" href="js/dc.css"/>
    <script src="js/crossfilter.js"></script>
    <script src="js/d3.js"></script>
    <script src="js/dc.js"></script>
</head>
<body>
    <div id="chart"></div>
</body>
<script>
    // generate data
    var min_value = 0, max_value = 18, value_range = max_value-min_value;
    var data = [];
    for (var i = 0; i < 1000; i++)
        data.push({x: math.random()*value_range+min_value});
    // create crossfilter dimension for column x
    var cf = crossfilter(data),
        x = cf.dimension(function(d) {return d.x;});
    // create histogram: group values to `number_of_bins` bins
    var number_of_bins = 10,
        bin_width = value_range/number_of_bins,
        //number_of_bins = value_range/bin_width,
        x_grouped = x.group(
            function(d) {return math.floor(d/bin_width)*bin_width;});
    // generate chart
    dc.barchart("#chart").dimension(x)
        .group(x_grouped)
        .x(d3.scale.linear().domain([min_value,max_value]))
        // let the bar widths be adjusted correctly
        .xunits(function(){return number_of_bins;})
        .xaxis();
    dc.renderall();
</script>

note that in this example it can also work to retrieve the number of bins or the bins' key values from the group object itself, e.g., like this

// number of bins
chart.xunits(function(){return x_grouped.all().length;});
// bins' key values
chart.xunits(function(){return x_grouped.all().map(function(d) {return d.key;});});

this will however fail (i.e., produce the wrong bar width), when there are empty bins.

for reference:


Related Query

More Query from same tag