Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a horizontal legend with d3.js

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?

like image 986
Martinffx Avatar asked Dec 19 '12 14:12

Martinffx


1 Answers

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
like image 136
cmonkey Avatar answered Nov 14 '22 23:11

cmonkey