本人的个人博客为: www.ourd3js.com
csdn博客为: blog.csdn.net/lzhlzz
转载请注明出处,谢谢。
D3中的坐标轴都是以 svg 图的形式出现的,这也是为什么在第3节中要使用 svg 的方法做柱形图的原因。第4节里我们讲解了 scale (比例)的用法,在做坐标轴的时候也需要用到比例。第4节中,我们说到scale 是一个函数,这一节中的坐标轴也是一个函数,但是用法却有点不同,要注意。
看下面的代码,我们分别定义数据,scale (比例),坐标轴:
var dataset = [ 30 , 20 , 45 , 12 , 21 ];
var xScale = d3.scale.linear()
.domain([0,d3.max(dataset)])
.range([0,500]);
var axis = d3.svg.axis()
.scale(xScale)
.orient("bottom"); 1-4行是定义数据和 scale (比例),关于比例的内容可看上一节。
5-7是定义坐标轴:
svg.append("g")
.call(axis); 在 svg 中添加一个g,g是 svg 中的一个属性,是 group 的意思,它表示一组什么东西,如一组 lines , rects ,circles 其实坐标轴就是由这些东西构成的。function foo(selection) {
selection
.attr("name1", "value1")
.attr("name2", "value2");
}
foo(d3.selectAll("div")) 这段代码等同于:d3.selectAll("div").call(foo); 所以 svg.append("g").call(axis) 就相当于将选择的g元素传给 axis 函数。 svg.append("g")
.attr("class","axis")
.attr("transform","translate(10,160)")
.call(axis); <style>
.axis path,
.axis line{
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = 600;
var height = 600;
var dataset = [ 30 , 20 , 45 , 12 , 21 ];
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
var xScale = d3.scale.linear()
.domain([0,d3.max(dataset)])
.range([0,500]);
var axis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
svg.append("g")
.attr("class","axis")
.attr("transform","translate(10,160)")
.call(axis);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x",10)
.attr("y",function(d,i){
return i * 30;
})
.attr("width",xScale) //注意这里
.attr("height",28)
.attr("fill","red");
</script> 
[5] D3.js中如何添加坐标轴,布布扣,bubuko.com
原文:http://blog.csdn.net/lzhlzz/article/details/34070839