By default, Flot with the Flot categories plugin doesn’t allow for you to use the ticks
or tickSize
option to show less ticks when there are too many data points on the x-axis for all of the labels to fit.
Our initial thought was to attempt to achieve this using a Ticks function inside the axis options. Unfortunately, this proved to be impossible due to the fact that the function appeared to run once for every tick on the axis, which would make it unworkable once we added the necessary computation.
Even more unfortunately, this meant resorting to hiding some of the labels using css when there wasn’t enough room for them to be displayed without overlapping. Even this hack was relatively complex.
function formatXTicks(axis){
var xWidth = $('.flot-x-axis').width();
var xTicks = $('.flot-x-axis .flot-tick-label').length;
console.log(xWidth/xTicks);
}
We started off just with the code above to find out the size of the available area and the number of ticks the flot chart wanted to use by default. We ran this on one of charts with an aesthetically pleasing number of ticks to find a good ratio to use and log it to the console.
In the final function below this figure would become xConst (our ideal was about 20). The function finds the inverse tick ratio (limiter) for the current graph, and, if it’s less than xConst (i.e. there are too many ticks for the space), does some mathsy wizardry in conjunction with a jquery each loop to hide all but the nth ticks. N in this case being equal to a rounding-down of the ideal ratio divided by the actual ratio.
function formatXTicks(axis){
var xWidth = $('.flot-x-axis').width();
var xTicks = $('.flot-x-axis .flot-tick-label').length;
var limiter = Math.floor(xWidth/xTicks);
var xConst = 20;
if(limiter < xConst){
$('.flot-x-axis .flot-tick-label').each(function(index){
if(index%Math.floor(xConst/limiter) > 0){
$(this).css("display","none");
}
})
}
}
Just call the function after your plot statement, and, hey presto, pretty axis labels again.
I’m in no doubt that there’s a far better, and faster, way of doing this, and if anybody has any suggestions please shout! However, this seems a lot less fiddly than reconfiguring the data formats on the server, and is good when practically all you know about the data is that there’s lots of it.
Connect on LinkedIn. Follow me on Twitter. Grab the RSS Feed