d3添加x軸y軸實(shí)例

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)軸就做好了~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容