I've been trying to create a horizontal legend for my graph using d3.js. I've struggled to get the x-axis spacing correct with dynamic labels.
The problem is that the labels are not of a consistent width, here's a full example and this is my function to calculate the x position:
function legendXPosition(data, position, avgFontWidth){
if(position == 0){
return 0;
} else {
var xPostiion = 0;
for(i = 0; i < position; i++){
xPostiion += (data[i].length * avgFontWidth);
}
return xPostiion;
}
}
Does anyone have any suggestions on how to improve this?
I suggest referencing this question: SVG get text element width
Render the first legend entry as you already are. Store this entry, or assign ids such that you can look them up through selection.
When rendering subsequent entries, get the previous 'text' element and x offset. Compute the new legend entry offset using the exact width of the previous text element
var myNewXOffset = myPreviousXOffset + myPreviousText.getBBox().width
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