座標軸作爲一個可視化圖表裏的組成部分,扮演者十分重要的角色。
d3.js裏定義了座標軸的繪製方法(個人翻譯,有錯誤請諒解):
• d3.axisTop – 創建一個座標軸生成器(top)
• d3.axisRight - 創建一個座標軸生成器(Right)
• d3.axisBottom - 創建一個座標軸生成器(Bottom)
• d3.axisLeft - 創建一個座標軸生成器(Left)
• axis – 生成座標軸
• axis.scale – 爲座標軸設置比例尺
• axis.ticks – 定義座標軸刻度生成方式(默認值爲)
• axis.tickArguments – 定義座標軸刻度參數
• axis.tickValues – 設置有特殊需求的刻度值(默認值爲null)
• axis.tickFormat – 設置有特殊需求的刻度格式(默認值爲null)
• axis.tickSize – 設置刻度的大小
• axis.tickSizeInner – 設置除兩端外所有刻度的長度(默認值爲6)
• axis.tickSizeOuter - 設置兩端刻度的長度(默認值爲6)
• axis.tickPadding – 設置刻度與文字之間距離(默認值爲3)
axis.ticks(5) 與 axis.tickArguments([5]) 的效果相同
axis.ticks(d3.timeMinute.every(10)) 可以生成時間刻度,同時也可以用
axis.tickArguments([d3.timeMinute.every(10)]) 來生成
var svg = d3.select("svg"),
margin = {top: 20, right: 20,bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var Format= d3.format(',.0f');
var x = d3.scaleLinear()
.range([0, width])
.domain([0,10]);
var y = d3.scaleLinear()
.range([height, 0])
.domain([20,0]);
var xAxis=d3.axisBottom()
.scale(x)
.ticks(5)
.tickValues([1, 2, 4, 8])
.tickFormat(function(d) { return '#' + Format(d); })
.tickSizeInner(5)
.tickSizeOuter(20)
.tickPadding(10);
var xAxis2=d3.axisTop()
.scale(x)
.tickArguments([5])
.tickValues([2, 3, 5, 7])
.tickFormat(function(d) { return Format(d)+ '*' ; })
.tickPadding(2);
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
g.append("g")
.attr("transform", "translate(0,0)")
.call(xAxis2);
g.append("g")
.call(d3.axisLeft(y));
g.append("g")
.attr("transform", "translate("+width+",0)")
.call(d3.axisRight(y));
這是上圖的代碼,比較簡單,如有錯誤請諒解。(本文使用d3.v4)