天天看點

可視化工具–D3–坐标軸的使用

坐标軸作為一個可視化圖表裡的組成部分,扮演者十分重要的角色。

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)

可視化工具–D3–坐标軸的使用

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:, right:,bottom:, left:},
            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(, width])
            .domain(]);

var y = d3.scaleLinear()
            .range([height,])
            .domain(]);

var xAxis=d3.axisBottom()
            .scale(x)
            .ticks)
            .tickValues(,,,])
            .tickFormat(function(d) { return '#' + Format(d); })
            .tickSizeInner)
            .tickSizeOuter)
            .tickPadding);

var xAxis2=d3.axisTop()
            .scale(x)
            .tickArguments(])
            .tickValues(,,,])
            .tickFormat(function(d) { return Format(d)+ '*' ; })
            .tickPadding);

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)

繼續閱讀