Skip to content

Instantly share code, notes, and snippets.

@ndarville
Forked from ZJONSSON/README.md
Last active December 17, 2015 14:49
Show Gist options
  • Save ndarville/5626890 to your computer and use it in GitHub Desktop.
Save ndarville/5626890 to your computer and use it in GitHub Desktop.

d3.legend

d3.legend is a quick hack to add a legend to a d3 chart. Simply add a g and .call(d3.legend). Any elements that have a title set in the "data-legend" attribute will be included when d3.legend is called. Each title will appear only once (even when multiple items define the same data-legend) as the process uses a set based on a existing names, not an array of all items.

Color

By default the color in the legend will try to match the fill attribute or the stroke attribute of the relevant items. Color can be explicitly defined by attribute "data-legend-color"

Order

The order of items in the legend will be sorted using the top of the bounding box for each included item. The order can be explicitly defined by attribute "data-legend-pos"

Padding

Padding will be determined by attribute "data-style-padding" on the legend element. Defaults to 5.

Size

Size of the box is determined by font size, as items are placed using "em" and the frame around the items is based on the bounding box.

This Example

This example takes an existing Gist and adds a legend by defining data-legend for each series and calling d3.legend on a "g" element. To show the font-adjustment I change font-size after one second and call d3.legend again.

d3.legend

d3.legend is a quick hack to add a legend to a d3.graph. Simply add a g and .call(d3.legend). Any elements that has a title set in the "data-legend" attribute set will be included, when d3.legend is called. Each title will appear only once as the process uses a set based on a existing names, not an array of all items.

Color

By default the color in the legend will try to match the fill attribute or the stroke attribute of the relevant items. Color can be explicitly defined by attribute "data-legend-color"

Order

The order of items in the legend will be sorted using the top of the bounding box for each included item. The order can be explicitly defined by attribute "data-legend-pos"

Padding

Padding will be determined by attribute "data-style-padding" on the legend element. Defaults to 5.

Size

Size of the box is determined by font size, as items are placed using "em" and the frame around the items is based on the bounding box.

This Example

This example takes an existing Gist and adds a legend by defining data-legend for each series:

 .attr("data-legend",function(d) { return d.name})

Adding the legend is as simple as:

legend = svg.append("g")
  .attr("class","legend")
  .attr("transform","translate(50,30)")
  .style("font-size","12px")
  .call(d3.legend)

To show the font-adjustment I change font-size after one second and call d3.legend again.

##Comments on the original gist This line chart is constructed from a TSV file storing the daily average temperatures of New York, San Francisco and Austin over the last year. The chart employs conventional margins and a number of D3 features:

// d3.legend.js
// (C) 2012 [email protected]
// MIT licence
(function() {
d3.legend = function(g) {
g.each(function() {
var g= d3.select(this),
items = {},
svg = d3.select(g.property("nearestViewportElement")),
legendPadding = g.attr("data-style-padding") || 5,
lb = g.selectAll(".legend-box").data([true]),
li = g.selectAll(".legend-items").data([true])
lb.enter().append("rect").classed("legend-box",true)
li.enter().append("g").classed("legend-items",true)
svg.selectAll("[data-legend]").each(function() {
var self = d3.select(this)
items[self.attr("data-legend")] = {
pos : self.attr("data-legend-pos") || this.getBBox().y,
color : self.attr("data-legend-color") != undefined ? self.attr("data-legend-color") : self.style("fill") != 'none' ? self.style("fill") : self.style("stroke")
}
})
items = d3.entries(items).sort(function(a,b) { return a.value.pos-b.value.pos})
li.selectAll("text")
.data(items,function(d) { return d.key})
.call(function(d) { d.enter().append("text")})
.call(function(d) { d.exit().remove()})
.attr("y",function(d,i) { return i+"em"})
.attr("x","1em")
.text(function(d) { ;return d.key})
li.selectAll("circle")
.data(items,function(d) { return d.key})
.call(function(d) { d.enter().append("circle")})
.call(function(d) { d.exit().remove()})
.attr("cy",function(d,i) { return i-0.25+"em"})
.attr("cx",0)
.attr("r","0.4em")
.style("fill",function(d) { console.log(d.value.color);return d.value.color})
// Reposition and resize the box
var lbbox = li[0][0].getBBox()
lb.attr("x",(lbbox.x-legendPadding))
.attr("y",(lbbox.y-legendPadding))
.attr("height",(lbbox.height+2*legendPadding))
.attr("width",(lbbox.width+2*legendPadding))
})
return g
}
})()
We can make this file beautiful and searchable if this error is corrected: No tabs found in this TSV file in line 0.
date ‰ on antidepressants
2002 58
2003 62
2004 63
2005 67
2006 71
2007 74
2008 76
2009 79
2010 84
2011 83
2012 82
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
.legend rect {
fill:white;
stroke:black;
opacity:0.8;}
</style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script src="d3.legend.js"></script>
<script>
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.temperature); });
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 + ")");
d3.tsv("data.tsv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
data.forEach(function(d) {
d.date = parseDate(d.date);
});
var cities = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, temperature: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(cities, function(c) { return d3.min(c.values, function(v) { return v.temperature; }); }),
d3.max(cities, function(c) { return d3.max(c.values, function(v) { return v.temperature; }); })
]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Temperature (ºF)");
var city = svg.selectAll(".city")
.data(cities)
.enter().append("g")
.attr("class", "city");
city.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.attr("data-legend",function(d) { return d.name})
.style("stroke", function(d) { return color(d.name); });
city.append("text")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")"; })
.attr("x", 3)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
legend = svg.append("g")
.attr("class","legend")
.attr("transform","translate(50,30)")
.style("font-size","12px")
.call(d3.legend)
setTimeout(function() {
legend
.style("font-size","20px")
.attr("data-style-padding",10)
.call(d3.legend)
},1000)
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment