Axes--D3 Interactive Data Visualization for the web

D3's axes are actually functions whose parameters you define. 


when an axis function is called, it doesn't return a value like scale, but generate the visual elements of the axis, including lines, labels

, and ticks.


Axis functions are SVG-specific, as they generate SVG elements. 


Set up an axis


1. 

// create a generic axis function

var xAxis = d3.svg.axis();


2. tell axis on what scale to operate

// pass scale to axis

xAxis.scale(xScale);


3. 

// specify where the labels appear relative to the axis itself.

xAxis.orient("bottom")


define axis function   :              var xAxis = d3.svg.axis()

                   .scale(xScale)

                 .orient("bottom");


4.  //call axis. Call axis at the end of script, so the axis appears on top

svg.append("g").attr("class","axis").call(xAxis); // although g isn't strictly necessary, we are using it because the axis function is about to generate lots of crazy lines and numbers. and it's nice to have those elements within a single group object. 


.call(function,[arguments...]) : this will invoke specified functions, this will return the current selection.



5.  // use CSS  to style axis; the axes itself is composed of path, line, text

.axis path, 

.axis line {

fill: none;

stroke: black;

shape-rendering: crispEdges;           // this can make axis and its tick mark lines are pixel-perfect; no blurry axes for us.

}

.axis text{

font-family:sans-serif;

font-size:11px;

}


6.  //transform the whole axes to the bottom

svg.append("g").attr("class","axis").attr("transform","translate(0,"+h-padding+")").call(xAxis);


translation transform: 平移變換


translate(x,y): x and y are the number of pixels by which to translate the element. 


7. Ticks: customize ticks 


                  var xAxis = d3. svg.axis()

.scale("xScale)

.orient("bottom")

.ticks(5); // the result is not necessary exactly 5 ticks, D3 will adjust this according to the range 



8.  yAxis

// set up an axis

var yAxis = d3.svg.axis()

.scale(yScale)

.orient("left")

.ticks(5);

  //call yAxis

svg.append("g").attr("class","axis").attr("transform","translate("+padding+",0)").call(yAxis);


9. Format Tick Labels


點擊打開鏈接 (python format spec)


var zero = d3.format("04d");      zero(2);//return 0002         zero(123); //return 0123


var formatAsPercentage = d3.format(".1%");

                                                 var yAxis = d3.svg.axis()
 .scale(yScale)
 .orient("left")
 .ticks(5)
 .tickFormat(formatAsPercentage);




發佈了52 篇原創文章 · 獲贊 18 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章