sparklines bar graph fit

javascript, jquery, sparklines

Solution

It will never fit perfectly because multiples of `count * (width + spacing)` may never fill the width exactly because they are rounded to integer values.

Best approximation I use now looks like that. (There is some additional code which reads the settings from data attributes.)

var $el = $(el);

var values = $el.data('values').split(',').map(parseFloat);
var type = $el.data('type') || 'line' ;
var height = $el.data('height') || 'auto';

var parentWidth = $el.parent().width();
var valueCount = values.length;
var barSpacing = 1;

var barWidth = Math.round((parentWidth - ( valueCount - 1 ) * barSpacing ) / valueCount);

$el.sparkline(values, {width:'100%', type: type, height: height, barWidth: barWidth, barSpacing: barSpacing});

The only optimisation left would be playing with the `barSpacing` parameter to reduce the difference between the product of the rounded barWidths and the parent width.

Problem

I'm using the sparklines package http://omnipotent.net/jquery.sparkline/#s-about I'm trying to make the sparklines bar graph fit to a predemined size, but I have many charts, and ideally this should be dynamic. I'm trying something like: ``` $.each(sparklines, function(index, sparkline) { var sparkline = $(sparkline); var data_out = sparkline.attr('data'); $.getJSON('/search/histogram/?histo_field=' + data_out, function (data) { var width = sparkline.width(); var data_obj = data.data; var l = data_obj.length; var pixel_width = parseInt((370-l) / l); sparkline.sparkline(data_obj, {type: 'bar', "barWidth":pixel_width,"height":50}) }); }); ``` The `parseInt((370-l) / l);` is to account for the spacing. The problem is, it's not fitting correctly. Especially when there are many such bars in the bar chart. It should be using exactly 370px, but in one case it's using 363px and in the other it's using 281. I tried just doing `parseInt(370) / l);` but that leaves an overhang of about ten px. Any thoughts?

Original source