A short demo of scatterplots with animated transitions, based on this example from the New York Times.
Last active
October 29, 2016 07:40
-
-
Save kpq/7348887 to your computer and use it in GitHub Desktop.
Dancing scatterplot
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> | |
<meta charset="utf-8"> | |
<style type="text/css"> | |
.dot { | |
fill:red; | |
} | |
</style> | |
<button id="button1" class="button b1">I am a button</button> | |
<button id="button2" class="button b2">I am another button</button> | |
<div class="scatterplot"></div> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<script type="text/javascript"> | |
// from here http://bl.ocks.org/mbostock/3019563 | |
var margin = {top: 20, right: 10, bottom: 20, left: 10}; | |
var width = 960 - margin.left - margin.right, | |
height = 500 - margin.top - margin.bottom; | |
var svg = d3.select(".scatterplot").append("svg") | |
.attr("width", width + margin.left + margin.right) | |
.attr("height", height + margin.top + margin.bottom) | |
.append("g") | |
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); | |
var x = d3.scale.linear() | |
.range([0, width]) | |
.domain([0,500]); | |
var y = d3.scale.linear() | |
.range([height, 0]) | |
.domain([0,10]); | |
d3.tsv("test.tsv", function(err, data) { | |
var dots = svg.selectAll(".dot") | |
.data(data) | |
.enter().append("circle") | |
.attr("class", "dot") | |
.attr("cx", function(d) { return x(d.x1); }) | |
.attr("cy", function(d) { return y(d.y1); }) | |
.attr("r", 5); | |
// this could obviously be made into a function, | |
// shown here for clarity, or because I'm lazy. | |
d3.selectAll(".button").on("click", function(d) { | |
var buttonId = d3.select(this).attr("id"); | |
if (buttonId == "button1") { | |
dots | |
.transition(1) | |
.attr("cx", function(d) { return x(d.x1) }); | |
} | |
if (buttonId == "button2") { | |
dots | |
.transition(1) | |
.attr("cx", function(d) { return x(d.x2) }); | |
} | |
}); | |
}); | |
</script> |
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
y1 | x1 | x2 | label | |
---|---|---|---|---|
1 | 145 | 20 | a | |
2 | 150 | 70 | b | |
3 | 180 | 120 | c | |
4 | 155 | 170 | d | |
5 | 160 | 220 | e | |
6 | 170 | 270 | f | |
7 | 190 | 320 | g | |
8 | 155 | 370 | h | |
9 | 165 | 420 | i | |
10 | 170 | 470 | j |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment