blue-sky
blue-sky

Reputation: 53916

Axis not displaying and alignment

Below code draws a circle and an x axis. There are a couple of problems. The y axis is not displayed but it is being added :

svgContainer.append('g')
        .attr("class", "axis")
        .call(yAxis);

The x axis is not being aligned to bottom but I have set the orientation to bottom :

orient("bottom").ticks(5);

here is complete code :

<!DOCTYPE html>
<html>
<head>

    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

</head>

<body>
    <script>

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

        var circle = svgContainer.append("circle")
                .attr("cx", 150)
                .attr("cy", 150)
                .attr("r", 100)
                .attr("fill", "none")
                .attr("stroke" , "red")
                .attr("stroke-width" , 2);

        var x = d3.scale.linear().range([0, 1000]);
        var y = d3.scale.linear().range([0, 1000]);

        var xAxis = d3.svg.axis().scale(x)
                .orient("bottom").ticks(5);

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

       svgContainer.append('g')
                .attr("class", "axis")
                .call(xAxis);

        svgContainer.append('g')
                .attr("class", "axis")
                .call(yAxis);

    </script>

</body>

</html>

fiddle : http://jsfiddle.net/zzz8svuq/1/

Why are these issues occurring ?

Upvotes: 0

Views: 25

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109292

Setting the orientation only affects the placement of the labels with respect to the axis line, D3 won't automatically position the axis on the canvas for you. The way this is usually done is to set a margin for the axes and offset the containers accordingly:

svgContainer.append('g')
            .attr("class", "axis")
            .attr("transform", "translate(" + margin + "," + (1000 - margin) + ")")
            .call(xAxis);

svgContainer.append('g')
            .attr("class", "axis")
            .attr("transform", "translate(" + margin + ",0)")
            .call(yAxis);

Complete demo here.

Upvotes: 1

Related Questions