Skip to content

Instantly share code, notes, and snippets.

@emeeks
Last active March 18, 2016 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emeeks/4c80fe802853f12fd0d6 to your computer and use it in GitHub Desktop.
Save emeeks/4c80fe802853f12fd0d6 to your computer and use it in GitHub Desktop.
Ch. 2, Fig. 21 - D3.js in Action

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.

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
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment