When you encode data with a circle, create a legend using the same scale.
forked from HarryStevens's block: Circles Legend
forked from lorenzopub's block: Circles Legend
xxxxxxxxxx
<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, function(d){ return 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", function(d){ return circle_scale(d) + 1; })
.attr("cx", circle_scale(max_data) + 1)
.attr("r", function(d){ return 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", function(d){ return circle_scale(d * 2) + 1; })
.attr("y2", function(d){ return 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", function(d){ return circle_scale(d * 2) + 5; })
.text(function(d, i){ return d + (i == legend_data.length - 1 ? " " + variable : ""); });
</script>
</body>
</html>
https://d3js.org/d3.v4.min.js