Skip to content

Instantly share code, notes, and snippets.

@alexandersimoes
Created October 28, 2011 17:26
Show Gist options
  • Save alexandersimoes/1322819 to your computer and use it in GitHub Desktop.
Save alexandersimoes/1322819 to your computer and use it in GitHub Desktop.
Assign multiple values to each node of data via CSV file
name population gdp
usa 788000000 2000000000
jpn 78000000 990000000
chn 150000000 345000000
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.3.0"></script>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.csv.js?2.3.0"></script>
</head>
<body>
<div id="chart"></div>
<script>
var svg = d3.select("#chart").append("svg:svg")
.attr("width", 200)
.attr("height", 600);
d3.csv("countries.csv", function(countries_csv) {
var nodes = countries_csv;
// Get min and max GDP to use in color function
var gdp_min = d3.min(nodes, function(d){
return parseInt(d["gdp"]);
});
var gdp_max = d3.max(nodes, function(d){
return parseInt(d["gdp"]);
});
// Size and Color will correspond to the log of GDP and Population
var size = d3.scale.log();
var color = d3.scale.log()
.domain([gdp_min,gdp_max])
.interpolate(d3.interpolateRgb)
.range(["skyblue", "steelblue"]);
// Draw circles to represent each "node" or country
svg.selectAll("circle")
.data(nodes) // assign csv data to correspond to each node
.enter().append("svg:circle")
// arbritrary position of x value corresponding to index of node
.attr("cx", function(d, i){
return (i+1)*150;
})
.attr("cy", 90)
// radius = log of population
.attr("r", function(d){
return Math.pow(size(parseInt(d["population"])), 2);
})
// color = log of GDP
.attr("fill", function(d){
return color(parseInt(d["gdp"]));
});
// Draw circles to represent each "node" or country
svg.selectAll("text")
.data(nodes)
.enter().append("svg:text")
.text(function(d){
return d["name"];
})
.attr("text-anchor", "middle")
.attr("x", function(d, i){
return (i+1)*150;
})
.attr("y", 90)
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment