I am having trouble adding a chart legend to my d3js chart. Here is my current approach:
var legend = svg.append("g")
.attr("class", "legend")
.attr("x", w - 65)
.attr("y", 25)
.attr("height", 100)
.attr("width", 100);
legend.append("rect")
.attr("x", w - 65)
.attr("y", 25)
.attr("width", 10)
.attr("height", 10)
.style("fill", function(d) { return color_hash[dataset.indexOf(d)][1] });
legend.append("text")
.attr("x", w - 65)
.attr("y", 25)
.text(function(d) { return color_hash[dataset.indexOf(d)][0] + ": " + d; });
Then I am attempting to style the .legend
class:
.legend {
padding: 5px;
font: 10px sans-serif;
background: yellow;
box-shadow: 2px 2px 1px #888;
}
But I'm not having much luck.
Is anyone familiar with adding legends to charts able to provide the best way to do so? I am not finding many resources for this online.
Here is my entire graph: http://jsbin.com/ewiwag/2/edit
Ok, here's one way to do it: http://jsbin.com/isuris/1/edit
Sorry, had to make too many changes to be able to explain it all. See if you can figure it out. If you have questions, ask the in the comments and I'll modify the answer.
You need to bind data to the nodes (rectangles and text elements) that make up the legend.
Currently you get an error when trying to style rectangles:
The reason: there's no bound data
Notice that D3 focuses on data transformation and operates on selections. So, first select a set of nodes and then bind data
Once you enter the selection with
enter
, you can add nodes and apply properties dynamically. Notice that to avoid creating rectangles on top of others, when setting they
property pass thei
counter and multiply it by an integer.Here's the fixed example: http://jsbin.com/ubafur/3