title: How to create a horizontal legend with d3.js
body: <p>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.</p>
  
  <p>The problem is that the labels are not of a consistent width, here's a <a href="http://bl.ocks.org/4336932" rel="nofollow">full example</a> and this is my function to calculate the x position:</p>
  
  <pre><code>function legendXPosition(data, position, avgFontWidth){
      if(position == 0){
          return 0;
      } else {
          var xPostiion = 0;
          for(i = 0; i &lt; position; i++){
              xPostiion += (data[i].length * avgFontWidth);
          }
          return xPostiion;
      }
  }
  </code></pre>
  
  <p>Does anyone have any suggestions on how to improve this?</p>