美文网首页d3(v5)
d3添加x轴y轴实例

d3添加x轴y轴实例

作者: 那头黑马 | 来源:发表于2019-08-28 16:10 被阅读0次

x轴y轴其实是line,但如果自己用svg的line一点点画肯定是很麻烦的,那d3就提供了丰富的API,来画xy轴,x轴包括axisTop()和axisBottom(),y轴包括axisLeft()和axisRight()。咱们平时用的坐标轴其实就是axisBottom()--x轴和axisLeft()--y轴,用了这2个API再加上比例尺,一个坐标轴就形成了。效果图:

p2.png

1.添加画布

var _svg = d3.select("body")
           .append("svg")
           .attr("width","600")
           .attr("height","300")
           .style("background","lightblue");

2.添加坐标轴g组

var _gAxis = _svg.append("g")
         .attr("transform","translate(25,25)");//相当于margin-top:25,margin-left:25;

3.添加包裹y轴的g组

var _gyaxis = _gAxis.append("g")
            .attr("id","gyaxis")
            .attr("transform","translate(50,50)");

4.创建比例尺

var _linescale = d3.scaleLinear()
            .domain([0,100]).nice()//nice用来优化数据  四舍五入等
            .range([150,0])//亦可以用rangeRound输出整数
            .clamp(true);

5.创建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用来优化数据  四舍五入等
            .range([0,150])//亦可以用rangeRound输出整数
            .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");

如图简单的坐标轴就做好了~

相关文章

网友评论

    本文标题:d3添加x轴y轴实例

    本文链接:https://www.haomeiwen.com/subject/twqmectx.html