未捕获的类型错误:无法读取未定义属性“axis”。

4

以下是我的代码片段:

<html> 
 <head> 
    <meta charset="utf-8">         
    <title>a picture</title> 
    <style>
        .axis path,
        .axis line{
            fill: none;
            stroke: black;
            shape-rendering: crispEdges;
        }

        .axis text{
            font-family: sans-serif;
            font-size: 11px;
        }
    </style>
 </head> 

    <body>
        <script src="http://d3js.org/d3.v4.min.js" charset="utf-8"></script>
        <script>
            var width=300; 
            var height=300; 

            var svg=d3.select("body")  
                      .append("svg")  
                      .attr("width",width)  
                      .attr("height",height); 

            var dataset = [ 2.5 , 2.1 , 1.7 , 1.3 , 0.9 ];  

            var linear = d3.scaleLinear()     
                           .domain([0, d3.max(dataset)])
                           .range([0, 250]);

            var rectHeight=25;  

            svg.selectAll("rect")
               .data(dataset)
               .enter()
               .append("rect")
               .attr("x",20)
               .attr("y",function(d,i){
                    return i * rectHeight;
            })
               .attr("width",function(d){
                    return linear(d);
            })
               .attr("height",rectHeight-2)
               .attr("fill","steelblue");

            var axis = d3.svg.axis()
                         .scale(linear)      
                         .orient("bottom")          
                         .ticks(7);         

            svg.append("g")
               .attr("class","axis")
               .attr("transform","translate(20,130)")
               .call(axis);

        </script>

    </body> 
</html>

这是我的代码,但当我使用它时,会出现错误:plot:53 Uncaught TypeError: Cannot read property 'axis' of undefined。在搜索了一些相关问题后,我认为可能是因为有更新,但我不知道该怎么处理,你能给我一个好的介绍吗?谢谢!

1个回答

2
您正在使用d3 v4.x版本。在这个新版本中,轴生成器函数已经发生了变化。
以下是正确的变量:
 var axis = d3.axisBottom(linear)
    .ticks(7);   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接