Skip to content

Instantly share code, notes, and snippets.

@MTClass
Created May 17, 2017 17:05
Show Gist options
  • Save MTClass/f42c5eba28a2640584afebc3666efd74 to your computer and use it in GitHub Desktop.
Save MTClass/f42c5eba28a2640584afebc3666efd74 to your computer and use it in GitHub Desktop.
Class 5 d3.legend
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<title>Class 5 v2</title>
<style>
body {
position: absolute;
margin: 0px;
font: 16px sans-serif;
}
svg {
background-color: #4682b4;
}
.info {
font-family: sans-serif;
color: #000;
position: absolute;
top: 450px;
left: 800px;
}
path {
fill: #555555;
stroke: #aaaaaa;
}
/* NEW: style the earthquakes */
path.quake {
fill: crimson;
}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<!-- NEW: Load the D3 legend plugin -->
<script src="d3.legend.js"></script>
<body>
<script>
var width = 960, height = 500;
var data; // declare a global variable
// NEW: Add a color scale
var colors = d3.scaleOrdinal()
.domain(['< 1', '1-2', '2-3', '3-4', '4-5', '> 5'])
.range(d3.schemeCategory10)
// NEW: Configure the legend
d3.legend = function() {
// Defaults
var t = [0, 0],
cb = null,
colors = d3.scaleOrdinal()
.domain(["A", "B", "C", "D"])
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b"]);
var box = 38,
padding = 2,
dx = box + padding;
function legend(selection) {
selection.each(function() {
var legend = d3.select(this).selectAll(".legend")
.data( colors.domain().slice().reverse() )
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(" + t[0] + "," + (t[1] + i * dx) + ")"; });
legend.append("rect")
.attr("x", 0 )
.attr("width", box)
.attr("height", box)
.style("fill", colors);
legend.append("text")
.attr("x", - 2 * padding )
.attr("y", box / 2)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
if (typeof cb == "function") cb();
})
}
legend.translate = function(_) {
if (!arguments.length) return t;
t = _;
return legend;
};
legend.colors = function(_) {
if (!arguments.length) return colors;
colors = _;
return legend;
};
legend.cb = function(_) {
if (!arguments.length) return cb;
cb = _;
return legend;
};
return legend;
}
var legend = d3.legend()
.translate([ width - 50 , height / 4 ])
.colors(colors);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.on("mousemove", mousemoved)
.call(legend); // NEW: Add the legend to the chart
var layer1 = svg.append("g");
var layer2 = svg.append("g");
// Add a <div> element to label the mouse position
var info = d3.select("body").append("div")
.attr("class", "info");
var projection = d3.geoAlbersUsa();
var path = d3.geoPath()
.projection(projection);
// Earthquake data
var usgs = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson";
// Topojson for US states
var url = "https://umbcvis.github.io/classes/class-03/us.json"
d3.json(url, plotStates);
d3.json(usgs, plotQuakes);
function plotStates(error, json) {
// Convert topojson to an Array of GeoJSON features
// This defines "data", a global variable that can be manipulated in the developer console
data = json.objects.us.geometries.map(function(d) { return topojson.feature(json, d); })
// Plot the features (states) -- one <path> element for each state
layer1.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d", path);
}
function plotQuakes(error, json) {
if (error) return console.log(error);
// Global variable, data, will be visible in the console
data = json;
// Extract an array of feature objects, one for each earthquake
var features = json.features;
// Plot the earthquakes
layer2.selectAll("path.quake")
.data(features)
.enter().append("path")
.attr("class", "quake")
.attr("d", path)
.style('fill', quakeColor); // NEW: Add magnitude-dependent color
// NEW: Function returns magnitude-dependent color for earthquakes
function quakeColor(d) {
var m = Math.min(Math.floor(Math.abs(d.properties.mag)), colors.domain().length);
var label = colors.domain()[m];
return colors(label);
}
}
// Label the geographic coordinates of the mouse position on the map
function mousemoved() {
info.text(formatLocation(projection.invert(d3.mouse(this)), projection.scale()));
}
// Format the text that will be displayed in the the <div> element on the map
function formatLocation(p, k) {
var format = d3.format("." + Math.floor(Math.log(k) / 2 - 2) + "f");
return (p[1] < 0 ? format(-p[1]) + "°S" : format(p[1]) + "°N") + " "
+ (p[0] < 0 ? format(-p[0]) + "°W" : format(p[0]) + "°E");
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment