Is there a way to overlay the x-axis and y-axis numeric labels onto a jQuery Flot graph. So, I want the labels to not be outside, next to the graph, but on top of the graph itself.
The following example creates an overlay div on top of the graph for the annotations: http://people.iola.dk/olau/flot/examples/annotating.html
Is there a straightforward way of grabbing the text and formatting of an axis from within flot and creating such an overlay out of it? Or, is there maybe another better way of overlaying the axis labels on top of the graph?
One way, which isn't particularly clean and especially won't work nicely if you plan to show x- and y-axis tick labels at the same time, is to set the labelMargin
option on the grid
to a negative value.
var plot = $.plot(placeholder, data, {
...
grid: { ..., labelMargin: -20, ... }
...
});
A second idea could be to grab all div
's which have class="tickLabel"
after the graph has been painted. And then "manually" alter their CSS positioning.
$("div.tickLabel").each(function(i,ele) {
ele = $(ele);
if (ele.css("text-align") == "center") { //x-axis
ele.css("top", ele.position().top - 20); //move them up over graph
} else { //y-axis
ele.css("left", ele.position().left + 20); //move them right over graph
}
});
Of course this still has some issues as the lowest tick label values on the x- and y-axis will overlap each other and the lowest/highest tick label values on the x- and y-axis will be positioned on the edges of the graph. But with some fine-tuning this might be a viable solution.
A third idea would be to directly use a tickFormatter
for the tick labels of the x- and y-axis. This works similar to the second idea but would place them directly where you want them to be without the maybe noticeable "label flickering" on repositioning which may occur with the function in the second idea.
var plot = $.plot(placeholder, data, {
...
xaxis: {
...,
tickFormatter: function formatter(val, axis) {
//return appropriately absolute positioned element
}
},
...
});
How this tickFormatter
function could look like is best derived by looking at the jQuery Flot sourcecode especially the function measureLabels
(this gets you an idea how Flot itself positions the tick labels) and the default tick formatter which looks like
function (v, axis) {
return v.toFixed(axis.tickDecimals);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With