【JavaScript】D3.js ~ 目盛を表示する ~

サンプル

y軸を出力

<html>
<head>
<meta charset="UTF-8">
<style>
.axis text {
    font-family: sans-serif;
    font-size: 11px;
}
.axis path,
.axis line {
    fill: none;
    stroke: black;
}
</style>
</head>
<body>
<div id="chart"></div>
<script src="">http://d3js.org/d3.v3.js">
<script>
var svg = d3.select("#chart").append("svg")
    .attr('width', 500)
    .attr('height', 1000);

// スケール
var yScale = d3.scale.linear()
    // 目盛の範囲(入力)
    .domain([500, 0])
    // 実際の出力サイズ(出力)
    .range([0, 200]);

var yAxis = d3.svg.axis()
    .scale(yScale)
    // 目盛の配置方向
    .orient('left')
    // 軸の刻み数。
    .ticks(5);

// 目盛を出力
svg.append('g')
    .attr('class', 'axis')
    // 目盛の表示位置
    .attr('transform', 'translate(50, 0)')
    .call(yAxis);
    
</script>
</body>
</html>

x軸を出力

<html>
<head>
<meta charset="UTF-8">
<style>
.axis text {
    font-family: sans-serif;
    font-size: 11px;
}
.axis path,
.axis line {
    fill: none;
    stroke: black;
}
</style>
</head>
<body>
<div id="chart"></div>
<script src="">http://d3js.org/d3.v3.js">
<script>
var svg = d3.select("#chart").append("svg")
    .attr('width', 500)
    .attr('height', 1000);

// スケール
var xScale = d3.scale.linear()
    // 目盛の範囲
    .domain([0, 500])
    // 実際の出力サイズ
    .range([0, 200]);

var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient('bottom')
    .ticks(5);
    
// 目盛を出力
svg.append('g')
    .attr('class', 'axis')
    .attr('transform', 'translate(10, 200)')
    .call(xAxis);
    
</script>
</body>
</html>

目盛に関するあれこれ

目盛のフォーマットを加える

* tickFormat() を使う
var yAxis = d3.svg.axis()
    .scale(yScale)
    .orient('left')
    .ticks(5)
    .tickFormat(function(d){ return d + " M"; }); // 数字に'M'をつけている

参考文献

http://www.openspc2.org/reibun/D3.js/code/graph/vertical-bar/1002/index.html
http://blog.livedoor.jp/kamikaze_cyclone/archives/34197135.html
http://dataisfun.org/2014/05/12/?p=193
http://ja.d3js.info/alignedleft/tutorials/d3/axes/
API in English
https://github.com/mbostock/d3/wiki/SVG-Axes