Legend update
HTML
<script src=" http://d3js.org/d3.v2.js"></script>
<div id="chart"></div>
CSS
.legend text {
font: 12px sans-serif;
fill: #000000;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
JavaScript
// Initialize SVG
var margin = {top: 10, right: 10, bottom: 30, left: 30},
width = 200 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
// Initialize legend
function update(data){
var legend = svg.selectAll("g.legend")
.data(data);
var legendEnter = legend.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legendEnter.append("rect")
.attr("width", 18)
.attr("height", 18);
legendEnter.append("text")
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end");
legend.select("rect")
.attr("x", width - 18)
.style("fill", color);
legend.select("text")
.attr("x", width - 24)
.text(function(d) { return d; });
legend.exit().remove();
}
// Data
var color = d3.scale.ordinal()
.domain(["Category 1", "Category 2"])
.range(["#ff7f0e", "#999999"]);
update(color.domain());
// Update data
color
.domain(["Group A", "Group B", "Group C"])
.range(["#6baed6", "#31a354", "#d62728"]);
update(color.domain());
console.log(d3.selectAll('text'), d3.select('text'));