x軸y軸其實(shí)是line,但如果自己用svg的line一點(diǎn)點(diǎn)畫肯定是很麻煩的,那d3就提供了豐富的API,來畫xy軸,x軸包括axisTop()和axisBottom(),y軸包括axisLeft()和axisRight()。咱們平時(shí)用的坐標(biāo)軸其實(shí)就是axisBottom()--x軸和axisLeft()--y軸,用了這2個(gè)API再加上比例尺,一個(gè)坐標(biāo)軸就形成了。效果圖:

p2.png
1.添加畫布
var _svg = d3.select("body")
.append("svg")
.attr("width","600")
.attr("height","300")
.style("background","lightblue");
2.添加坐標(biāo)軸g組
var _gAxis = _svg.append("g")
.attr("transform","translate(25,25)");//相當(dāng)于margin-top:25,margin-left:25;
3.添加包裹y軸的g組
var _gyaxis = _gAxis.append("g")
.attr("id","gyaxis")
.attr("transform","translate(50,50)");
4.創(chuàng)建比例尺
var _linescale = d3.scaleLinear()
.domain([0,100]).nice()//nice用來優(yōu)化數(shù)據(jù) 四舍五入等
.range([150,0])//亦可以用rangeRound輸出整數(shù)
.clamp(true);
5.創(chuàng)建y軸,并映射比例尺
var _yaxis = d3.axisLeft()
.scale(_linescale)
.ticks(5)//分5段
// .tickValues([0,25,50,75,100])//自定義刻度
//.tickFormat(d3.format("%"))//刻度的格式化
;
6.將y軸添加到畫布上
_gyaxis.call(_yaxis);
7.定義y軸樣式
d3.select("#gyaxis")
.selectAll("text")
.attr("fill","blue")
.style("font-size","24px")
.style("transform","rotate(-45deg)");
d3.select("#gyaxis")
.selectAll("path")
.attr("stroke","blue")
.style("width","4");
d3.select("#gyaxis")
.selectAll("line")
.attr("stroke","blue");
8.像如上步驟添加x軸
var _gxaxis = _gAxis.append("g")
.attr("id","gxaxis")
.attr("transform","translate(50,200)");//200=50+150
var _linescaleX = d3.scaleLinear()
.domain([0,100]).nice()//nice用來優(yōu)化數(shù)據(jù) 四舍五入等
.range([0,150])//亦可以用rangeRound輸出整數(shù)
.clamp(true);
var _xaxis = d3.axisBottom()
.scale(_linescaleX)
.ticks(5);
_gxaxis.call(_xaxis);
d3.select("#gxaxis")
.selectAll("text")
.attr("fill","blue")
.style("font-size","24px")
.style("transform","rotate(-45deg)");
d3.select("#gxaxis")
.selectAll("path")
.attr("stroke","blue")
.style("width","4");
d3.select("#gxaxis")
.selectAll("line")
.attr("stroke","blue");
如圖簡單的坐標(biāo)軸就做好了~