Setting x axis labels position with D3.js

时间:2016-07-11 20:04:44

标签: javascript d3.js axis-labels

I have a problem setting the x axis for a simple visualization made with D3.js. I have something like the following image: enter image description here

Obtained with this code (taken from an example I'm following):

    var start_year = 2006, end_year = 2015;

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

    var xAxis = d3.svg.axis().scale(x).orient("top");

    var formatYears = d3.format("0000");
    xAxis.tickFormat(formatYears);

    var svg = d3.select("#page_content").append("svg")
            .attr("width", "100%")
            .attr("height", "100%")
            .style("margin-left", 0)
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    x.domain([start_year, end_year]);

    var xScale = d3.scale.linear()
            .domain([start_year, end_year])
            .range([0, width]);

    var g = svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + 0 + ")")
            .call(xAxis);

The problem is that I'm dealing with football seasons, so I would like to have for the x axis domain something like "2006/2007", "2007/2008" and so on.

I tried by creating an array of strings and using it as x domain:

    domain_data = ["2006-2007","2007-2008","2008-2009","2009-2010","2010-2011","2011-2012","2012-2013","2013-2014","2014-2015","2015-2016"];

    var x = d3.scale.ordinal().rangeRoundBands([0, width]);

    var xAxis = d3.svg.axis().scale(x).orient("top");

    var svg = d3.select("#page_content").append("svg")
            .attr("width", "100%")
            .attr("height", "100%")
            .style("margin-left", 0)
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    x.domain(domain_data.map(function(d) { return d; }));

    var xScale = d3.scale.linear()
            .domain([start_year, end_year])
            .range([0, width]);

    var g = svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + 0 + ")")
            .call(xAxis);

but, as you can see from the following image, each label is slightly shifted on the right or on the left with respect to the circles. With an array of strings as domain

I'm very new to D3.js so if someone can explain me how to fix this problem, or maybe a better solution to achieve my goal, it'll be very helpful. Thanks in advance

** * EDIT: Added a JSFiddle * **

This is the JSFiddle you asked, hope it helps finding the solution. Thank you

0 个答案:

没有答案