An example of d3-contour.
Last active
March 6, 2019 05:07
-
-
Save mbostock/f48ff9c1af4d637c9a518727f5fdfef5 to your computer and use it in GitHub Desktop.
Contour Plot II
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
license: gpl-3.0 | |
redirect: https://observablehq.com/@d3/contours |
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> | |
<svg width="960" height="500" stroke="#fff" stroke-width="0.5"></svg> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script src="https://d3js.org/d3-contour.v1.min.js"></script> | |
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> | |
<script> | |
// Populate a grid of n×m values where -2 ≤ x ≤ 2 and -2 ≤ y ≤ 1. | |
var n = 240, m = 125, values = new Array(n * m); | |
for (var j = 0.5, k = 0; j < m; ++j) { | |
for (var i = 0.5; i < n; ++i, ++k) { | |
values[k] = goldsteinPrice(i / n * 4 - 2, 1 - j / m * 3); | |
} | |
} | |
var svg = d3.select("svg"), | |
width = +svg.attr("width"), | |
height = +svg.attr("height"); | |
var thresholds = d3.range(1, 21) | |
.map(function(p) { return Math.pow(2, p); }); | |
var contours = d3.contours() | |
.size([n, m]) | |
.thresholds(thresholds); | |
var color = d3.scaleLog() | |
.domain(d3.extent(thresholds)) | |
.interpolate(function() { return d3.interpolateYlGnBu; }); | |
svg.selectAll("path") | |
.data(contours(values)) | |
.enter().append("path") | |
.attr("d", d3.geoPath(d3.geoIdentity().scale(width / n))) | |
.attr("fill", function(d) { return color(d.value); }); | |
// See https://en.wikipedia.org/wiki/Test_functions_for_optimization | |
function goldsteinPrice(x, y) { | |
return (1 + Math.pow(x + y + 1, 2) * (19 - 14 * x + 3 * x * x - 14 * y + 6 * x * x + 3 * y * y)) | |
* (30 + Math.pow(2 * x - 3 * y, 2) * (18 - 32 * x + 12 * x * x + 48 * y - 36 * x * y + 27 * y * y)); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment