This is the code for Chapter 2, Figure 25 from D3.js in Action that draws a scatterplot from loaded JSON data. For each datapoint in the loaded data, an SVG g element is rendered, each of which has an SVG circle and SVG text element as children. The g element is placed according to the attributes of the data, while the circle element is sized according to the data and the text element has its .text() populated from the data.
xxxxxxxxxx
<html>
<head>
<title>D3 in Action Chapter 2 - Example 12</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.json("tweets.json",function(error,data) {dataViz(data.tweets)});
function dataViz(incomingData) {
incomingData.forEach(function (el) {
el.impact = el.favorites.length + el.retweets.length
el.tweetTime = new Date(el.timestamp);
})
var maxImpact = d3.max(incomingData, function(el) {return el.impact});
var startEnd = d3.extent(incomingData, function(el) {return el.tweetTime});
var timeRamp = d3.time.scale().domain(startEnd).range([20,480]);
var yScale = d3.scale.linear().domain([0,maxImpact]).range([0,460]);
var radiusScale = d3.scale.linear().domain([0,maxImpact]).range([1,20]);
var colorScale = d3.scale.linear().domain([0,maxImpact]).range(["white","#990000"]);
var tweetG = d3.select("svg")
.selectAll("g")
.data(incomingData)
.enter()
.append("g")
.attr("transform", function(d) {
return "translate(" +
timeRamp(d.tweetTime) + "," + (480 - yScale(d.impact))
+ ")"
})
tweetG.append("circle")
.attr("r", function(d) {return radiusScale(d.impact)})
.style("fill", "#990000")
.style("stroke", "black")
.style("stroke-width", "1px")
tweetG.append("text")
.text(function(d) {return d.user + "-" + d.tweetTime.getHours()});
}
</script>
</footer>
</html>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js