Skip to content

Instantly share code, notes, and snippets.

@HarryStevens
Last active June 12, 2018 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarryStevens/b779b431075d1a2c5710e9b826736650 to your computer and use it in GitHub Desktop.
Save HarryStevens/b779b431075d1a2c5710e9b826736650 to your computer and use it in GitHub Desktop.
Circles Legend
height: 110
license: gpl-3.0

When you encode data with a circle, create a legend using the same scale.

<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
font-family: "Helvetica", sans-serif;
}
#legend {
margin: 0 auto;
display: table;
}
.legend-circle {
fill: none;
stroke: #000;
}
.legend-dotted-line {
stroke: #000;
stroke-dasharray: 2, 2;
shape-rendering: crispEdges;
}
.legend-number {
font-size: .7em;
}
</style>
</head>
<body>
<div id="legend"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = [{name: "Andrew", value: 237}, {name: "Bob", value: 120}],
variable = "value",
max_circle_size = 50,
max_data = d3.max(data, d => d[variable]),
circle_scale = d3.scaleLinear()
.range([0, max_circle_size])
.domain([0, max_data]),
legend_text_left_pad = 8,
legend_width = max_circle_size * 3,
legend_height = max_circle_size * 2 + 10,
legend = d3.select("#legend").append("svg")
.attr("width", legend_width)
.attr("height", legend_height),
legend_data = [max_data, 150, 50],
legend_circle = legend.selectAll(".legend-circle")
.data(legend_data)
.enter().append("circle")
.attr("class", "legend-circle")
.attr("cy", d => circle_scale(d) + 1)
.attr("cx", circle_scale(max_data) + 1)
.attr("r", d => circle_scale(d)),
legend_dotted_line = legend.selectAll(".legend-dotted-line")
.data(legend_data)
.enter().append("line")
.attr("class", "legend-dotted-line")
.attr("x1", circle_scale(max_data) + 1)
.attr("x2", circle_scale(max_data) * 2 + legend_text_left_pad)
.attr("y1", d => circle_scale(d) * 2 + 1)
.attr("y2", d => circle_scale(d) * 2 + 1),
legend_number = legend.selectAll(".legend-number")
.data(legend_data)
.enter().append("text")
.attr("class", "legend-number")
.attr("x", circle_scale(max_data) * 2 + legend_text_left_pad)
.attr("y", d => circle_scale(d) * 2 + 5)
.text((d, i) => d + (i == legend_data.length - 1 ? " " + variable : ""));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment