How do I set custom ticks along the Xaxis in D3? or name the bars in a bar chart?

10,512

Ah, I see you were using a linear scale. In this case you need an ordinal scale, since the domain is a set of discrete values (the list of titles).

Working example: http://tributary.io/inlet/5775047 There are comments in the code for the axis part.

The issue is that the range array needs to have as many values as there are labels in the domain array. Otherwise it recycles. In your case, the first label was on 0, then w, then 0, then w, and so on.

To get the titles dynamically from the array of data, you need to use the map method on the array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Working example with dynamic titles: http://tributary.io/inlet/5775215

Share:
10,512
Keith Johnson
Author by

Keith Johnson

I'm a full-stack web developer specializing in ruby and javascript, particularly ember.js. I recently quit my job to teach myself how to code artificial intelligence.

Updated on August 06, 2022

Comments

  • Keith Johnson
    Keith Johnson over 1 year

    I'm trying to create a bar chart with custom values for each bar along the xAxis in D3, and thought I'd try to use the tickValues. Just to try it out I gave it some dummy data but it doesn't work like this:

      var xAxis = d3.svg.axis()
        .scale(xScale)
        .orient("bottom")
    
        .tickValues(['hi','b','c','d','e']);
    

    Here's the xScale:

    gon.votes.length is an array of total votes counts for EACH answer and functionally is there only to return how many bars there will be for a specific survey question(this is a survey app fyi)

      var xScale = d3.scale.linear()
        .domain([0,gon.votes.length])
        .range([0,w]);
    

    Finally, when I call

    function(d){ return d.title}
    

    This will extract the appropriate title for each bar.

    Also here is the html of the ticks of the xAxis that gets rendered: NaN

    Any tips on how to put this along the xAxis? Is trying to modify the ticks the wrong approach?