When you encode data with a circle, create a legend using the same scale.
Last active
June 12, 2018 14:50
-
-
Save HarryStevens/b779b431075d1a2c5710e9b826736650 to your computer and use it in GitHub Desktop.
Circles Legend
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
height: 110 | |
license: gpl-3.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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