title: d3.js Get Legend Outside of Chart
body: <p>I am trying to get the legend of my chart outside of the charting area. </p>
  
  <p>Here are the margins:</p>
  
  <pre><code>var margin = {top: 50, right: 200, bottom: 50, left: 40};
          var width = 960 - margin.left - margin.right,
              height = 500 - margin.top - margin.bottom;
  </code></pre>
  
  <p>First I create the svg:</p>
  
  <pre><code>var svg = d3.select("body").append("svg")
              .attr("width", width + margin.left + margin.right)
              .attr("height", height + margin.top + margin.bottom)
              .append("g")
                  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
  </code></pre>
  
  <p>So, from my understanding, I now have the svg canvas element and a g inside of it which holds the chart.  I am trying to add more to the right margin, so I can get some space between the svg canvas and the g appended to it, which holds the chart.  Then I want to put my legend in that empty space. </p>
  
  <p>Here is where I add my legend:</p>
  
  <pre><code>//add legend
              var legend = svg.append("g")
                  .attr("class", "legend")
                  .attr("height", 300)
                  .attr("width", 200)
                  .attr("transform", "translate(-1000,50");
  </code></pre>
  
  <p>Even though I am appending to the SVG element, it is appending to the g within the svg element.  So, no matter how much I translate it or try to get it to go more right on the screen, it never goes past the width of the inner g.  </p>
  
  <p>When troubleshooting, I see that the outer SVG element has a height of 960 and width of 500. The g appended to that has a transform/translate of 40,50.  The width ends up being 839px by 433.223px (not sure I understand this).  The outer svg has a bunch of space to the right now because of the margin built in.</p>
  
  <p>So I'm trying to either increase the width of the g appended to the svg so I can put my legend as a child of the g and move it to the empty space created by the margin.  Or, I'm trying to create another g that is a sibling to the first g and then I can use the empty space created by the margin.  </p>
  
  <p>I can't get either to work and don't know which way is best. </p>