Stefan I
Stefan I

Reputation: 1

d3 axes not appearing

I'm having a problem getting the axes to actually show on my bar graph, so far without any luck as I just can't seem to wrap my head around what's wrong. Is it something to do with the scaling?

Is the axis rendering but being cut out of the svg by the bars?

<script type="text/javascript">


    //Width and height
    var w = 850;
    var h = 650;
    var barpadding = 20;


    var dataset = [40, 99];


    //Create SVG element
    var svg = d3.select(".wrapper")
            .append("svg")
            .attr("width", w)
            .attr("height", h);

    //Create scale functions
    var x = d3.scaleBand()
            .range([0, w])
            .padding(0.1);
    var y = d3.scaleLinear()
            .range([h, 0]);


    svg.selectAll("rect")
            .data(dataset)
            .enter()
            .append("rect")
            .attr("x", function (d, i) {
                return i * (w / dataset.length);
            })
            .attr("y", function (d) {
                return h - (d * 4);
            })
            .attr("width", w / dataset.length - barpadding)
            .attr("height", function (d) {
                return d * 4;
            })
            .attr("fill", "dodgerblue");

    svg.selectAll("text")
            .data(dataset)
            .enter()
            .append("text")
            .text(function (d) {
                return d;
            })
            .attr("text-anchor", "middle")
            .attr("x", function (d, i) {
                return i * (w / dataset.length) + (w / dataset.length - barpadding) / 2;
            })
            .attr("y", function (d) {
                return h - (d * 4) + 14;
            })
            .attr("font-family", "sans-serif")
            .attr("font-size", "18px")
            .attr("fill", "black");

    d3.select(".axis")
            .call(d3.axisBottom(x));

</script>

Upvotes: 0

Views: 31

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

For showing the axis, you'll have to append a <g> element first. After that, since the axes are always generated at the origin (0,0), you'll have to translate it down and, only then, calling the axis:

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + someValue + ")")
    .call(d3.axisBottom(x));

I normally provide a working demo, but this time I'll skip it, because your code has some problems:

  • It lacks the margins for the axis
  • It lacks the domains of the scales
  • It position the bars using magic numbers, not the scales

But, if you want to see your code with the axis 20px above the bottom, this is how it looks like: https://jsfiddle.net/qcnako3g/

Upvotes: 1

Related Questions