Skip to content

Instantly share code, notes, and snippets.

@aogriffiths
Created June 12, 2012 06:17
Show Gist options
  • Save aogriffiths/2915561 to your computer and use it in GitHub Desktop.
Save aogriffiths/2915561 to your computer and use it in GitHub Desktop.
d3 data changes
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>2915561-d3-data-changes</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
Demonstrates some simple d3 transitions based on data.
Issue:
The three red rectangles change colour AND size. But the three blue rectangles
change colour only.
see it more clearly at http://bl.ocks.org/2915561
<html lang="en">
<head>
<title>D3 Transitions</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<!-- JS -->
<!--
<script type="text/javascript" src="https://raw.github.com/mbostock/d3/master/d3.min.js"></script>
-->
<script type="text/javascript" src="../2902093/d3.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="vis"></div>
<script type="text/javascript">
main();
</script>
</body>
</html>
function main() {
var data = [ 10, 20, 30 ];
var data2 = [ 40, 30, 20 ];
var svg = d3.select("#vis")
.append("svg")
.attr("width", 800)
.attr("height", 300);
//Three rects for scenario 1:
var g1 = svg.selectAll("g.items1")
.data(data)
.enter()
.append("g")
.attr("class", 'items1');
var r1 = g1
.append("rect")
.attr("class", 'r1')
.attr("fill", "red")
.attr("height", 20)
.attr("x", 0)
.attr("y", function(d,i){return i*25})
.attr("width", function(d){return d});
//Same three rects for scenario 2:
var g2 = svg.selectAll("g.items2a")
.data(data)
.enter()
.append("g")
.attr("class", 'items2');
var r2 = g2
.append("rect")
.attr("class", 'r2')
.attr("fill", "blue")
.attr("height", 20)
.attr("x", 50)
.attr("y", function(d,i){return i*25})
.attr("width", function(d){return d});
//Transition 1, works
svg.selectAll("g.items1")
.data(data2)
r1 = g1.select("rect.r1"); //the three rect's are selected from the three g's
r1
.transition()
.attr("fill", "darkred")
.duration(2000)
.attr("width", function(d){return d});
//Transition 1, fails
svg.selectAll("g.items2")
.data(data2);
r2 = svg.selectAll("rect.r2"); //the three rect's are selected from the single svg
r2
.transition()
.attr("fill", "darkblue")
.duration(1000)
.attr("width", function(d){return d});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment