Maximilian Hf Maximilian Hf - 5 months ago 115
Javascript Question

Can't add an axis in d3.js

I am learning d3.js for a project I am doing at my university.
My problem is when I append an axis to my svg object, the whole svg vanishes from the site in the browser. I've also tried using some of the code examples like this, but it's not working either.

Here is my code:

<!DOCTYPE HTML>
<html>
<head>
<title>Data</title>
<script src="https://d3js.org/d3.v4.0.0-alpha.44.min.js"></script>
</head>
<body>
<script>

var data_1 = [23, 54, 67, 12, 4];
var data_2 = [1, 2, 3, 4, 5];

var width = 800;
var height = 800;

var mapScale = d3.scaleLinear()
.domain([0, 70])
.range([0, width - 40]);

var axisBot = d3.svg.axis();
.scale(mapScale);

var axisLft = d3.axisLeft(data_1);


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


var xsCont = canvas.append('g')
.call('axisBot');

var lines = canvas.selectAll('rect')
.data(data_1)
.enter()
.append('rect')
.attr('width', function(d) { return mapScale(d); })
.attr('height', 20)
.attr('y', function(d, i) { return i * 100 });

</script>
</body>
</html>

Answer

Here is the code after correction.

<!DOCTYPE HTML>
<html>
<head>
    <title>Data</title>
    <script src="https://d3js.org/d3.v4.0.0-alpha.44.min.js"></script>
</head>
<body>
    <script>

        var data_1 = [23, 54, 67, 12, 4];
        var data_2 = [1, 2, 3, 4, 5];

        var width = 800;
        var height = 800;

        var mapScale = d3.scaleLinear()
                            .domain([0, 70])
                            .range([0, width - 40]);

        var axisBot = d3.axisBottom(mapScale);

        var axisLft = d3.axisLeft(data_1);


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


        var xsCont = canvas.append('g')
                            .call(axisBot);

        var lines = canvas.selectAll('rect')
                            .data(data_1)
                            .enter()
                                .append('rect')
                                .attr('width', function(d) { return mapScale(d); })
                                .attr('height', 20)
                                .attr('y', function(d, i) { return i * 100 });

    </script>
</body>
</html>

And that's the result: enter image description here

Issue 1

var axisBot = d3.svg.axis();
                        .scale(mapScale);

You see? the method chaining is broken, you should remove the ;

Issue 2

Issue 1 is not really matter, because in d3 v4, there is no d3.svg.axis (https://github.com/d3/d3-axis). You should use d3.axisBottom/d3.axisTop/d3.axisRight/d3.axisLeft

Issue 3

 var xsCont = canvas.append('g') 
   .call('axisBot');`

You should call a method/function here, instead of a string, which means you should remove the '.

Comments