Axes

SVG Axes

1. Setting Up an Axis

1
2
3
4
5
6
7
8
9
10
var xAxis = d3.svg.axis();
xAxis.scale(xScale);
xAxis.orient("bottom");
# 一步到位
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
# 添加
svg.append("g")
.call(xAxis);

2. style SVG elements

SVG Attribute reference

1
2
3
svg.append("g")
.attr("class", "axis") //Assign "axis" class
.call(xAxis);

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
```

#### 3. [SVG transformations](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform)

Note that we use attr() to apply transform as an attribute of g.

svg.append(“g”)
.attr(“class”, “axis”)
.attr(“transform”, “translate(0,” + (h - padding) + “)”)
.call(xAxis);

1
2
3
4
5

<!-- more -->

#### 4. Ticks
Ticks communicate information and can also clutter your chart.

var xAxis = d3.svg.axis()
.scale(xScale)
.orient(“bottom”)
.ticks(5); //Set rough # of ticks

1
2

#### 5. Y axis

//Define Y axis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient(“left”)
.ticks(5);
//Create Y axis
svg.append(“g”)
.attr(“class”, “axis”)
.attr(“transform”, “translate(“ + padding + “,0)”)
.call(yAxis);

1
2
3

#### 6. Formatting Tick Labels
[d3 formatting](https://github.com/mbostock/d3/wiki/Formatting#d3_format)

var formatAsPercentage = d3.format(“.1%”);
xAxis.tickFormat(formatAsPercentage);
```

Comments