-->

D3 - using strings for axis ticks

2020-02-24 13:11发布

问题:

I want to crate a bar chart using strings as the labels for the ticks on the x-axis (e.g., Year 1, Year 2, etc instead of 0,1,2, etc).

I started by using the numeric values for the x-axis (e.g., 0,1,2,3, etc) as follows:

1) I generate my ranges:

     x = d3.scale.ordinal()
        .domain(d3.range(svg.chartData[0].length)) //number of columns is a spreadsheet-like system
        .rangeRoundBands([0,width], .1); 


     y = d3.scale.linear()
        .domain(Math.min(d3.min(svg.chartData.extent),0), Math.max(d3.min(svg.chartData.extent),0)]) 
        .range([height, 0])
        .nice();

2) Make the axes:

     d3.svg.axis()
        .scale(x);

3) Redraw the axes:

     svg.select(".axis.x_axis")
        .call(make_x_axis().orient("bottom").tickSubdivide(1).tickSize(6, 3, 0));

This works well with default numeric axis labels.

If I try to use an array of strings for the x tickValues like this....

     d3.svg.axis()
        .scale(x).tickValues(svg.pointsNames); //svg.pointsNames = ["Year 1", "year 2", etc.]

... when I redraw the chart (with or without changes to the data/settings), the labels swap like this.

Notice how Col 1 takes the place of Col 0 and vice versa.

Do you know why this happens?

回答1:

Update

Just sort the svg.pointsNames before you apply them as tickValues. Make sure you sort them in exactly the same way that you sort your data. This way, a one-one mapping is always maintained between your labels and tick values.

Also if I may, check out the tickFormat` function here. This seems a better option to me.

//Tick format example
chart,xAxis.tickFormat(function(d, i){
    return "Year" + d //"Year1 Year2, etc depending on the tick value - 0,1,2,3,4"
})


回答2:

Thanks for that...I used this function with an inline if-clause to handle a different x-axis series with names instead of numbers.

The factions Array consists of all relevant names sorted by the indexes of the series who then just get matched with its corresponding index in the data.

xAxis = d3.svg.axis().scale(xScale)
            .tickFormat(function(d) { 

                if(seriesX == 'seriesValue'){ 
                    return factions[d]}

                else{ 
                    return d}
            })    
         .orient("bottom");