block by emeeks c99dd371eb2dbb2dab5c

Ch. 4, Fig. 9 - D3.js in Action

Full Screen

This is the code for Chapter 4, Figure 9 from D3.js in Action demonstrating how to offset d3.svg.axis() elements by changing the axis settings.

index.html

<html>
<head>
  <title>D3 in Action Chapter 4 - Example 5</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;
  }
line {
  shape-rendering: crispEdges;
  stroke: #000000;
  }

line.minor  {
  stroke: #777777;
  stroke-dasharray: 2,2;
}

path.domain {
  fill: none;
  stroke: black;
}

</style>
<body>

<div id="viz">
  <svg>
  </svg>
</div>
</body>
  <footer>
    
<script>
var scatterData = [{friends: 5, salary: 22000}, {friends: 3, salary: 18000}, {friends: 10, salary: 88000}, {friends: 0, salary: 180000}, {friends: 27, salary: 56000}, {friends: 8, salary: 74000}]

xScale = d3.scale.linear().domain([0,180000]).range([0,480]);
yScale = d3.scale.linear().domain([0,27]).range([0,480]);
    
xAxis = d3.svg.axis().scale(xScale).orient("bottom").tickSize(480).ticks(4);
d3.select("svg").append("g").attr("id", "xAxisG").call(xAxis);

yAxis = d3.svg.axis().scale(yScale).orient("right").ticks(10).tickSize(480).tickSubdivide(10);

d3.select("svg").append("g").attr("id", "yAxisG").call(yAxis);

d3.select("svg").selectAll("circle").data(scatterData).enter().append("circle").attr("r", 5)
.attr("cx", function(d) {return xScale(d.salary)}).attr("cy", function(d) {return yScale(d.friends)})


</script>
  </footer>

</html>