block by emeeks 4c80fe802853f12fd0d6

Ch. 2, Fig. 21 - D3.js in Action

Full Screen

This is the code for Chapter 2, Figure 21 from D3.js in Action loading data from an external CSV, measuring one of the fields of that data using d3.max, and then creating a scale based on that measurement to draw the data as a bar chart.

index.html

<html>
<head>
  <title>D3 in Action Chapter 2 - Example 9</title>
  <meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>
<style>
  svg {
    height: 500px;
    width: 500px;
    border: 1px solid gray;
  }
</style>
<body>

<div>
  <svg>
  </svg>
</div>
</body>
  <footer>
    
<script>
d3.csv("cities.csv",function(error,data) {dataViz(data)});
function dataViz(incomingData) {

maxPopulation = d3.max(incomingData, 
function(el) {return parseInt(el.population)}
);
var yScale = d3.scale.linear().domain([0,maxPopulation]).range([0,460]);

d3.select("svg")
.selectAll("rect")
.data(incomingData)
.enter()
.append("rect")
.attr("width", 50)
.attr("height", function(d) {return yScale(parseInt(d.population))})
.attr("x", function(d,i) {return i * 60})
.attr("y", function(d) {return 480 - yScale(parseInt(d.population))})
.style("fill", "blue")
.style("stroke", "red")
.style("stroke-width", "1px")
.style("opacity", .25)
}

</script>
  </footer>

</html>

cities.csv

"label","population","country","x","y"
"San Francisco", 750000,"USA",37,-122
"Fresno", 500000,"USA",36,-119
"Lahore",12500000,"Pakistan",31,74
"Karachi",13000000,"Pakistan",24,67
"Rome",2500000,"Italy",41,12
"Naples",1000000,"Italy",40,14
"Rio",12300000,"Brazil",-22,-43
"Sao Paolo",12300000,"Brazil",-23,-46