Search code examples
javascriptchartsrickshaw

Display custom labels on X-axis with Rickshaw JS library


I have a dataset with pairs {x: someValue, y: count} where someValue is a day of the week in a form of (1..7) where 1 is "Sunday". On the Ricskshaw chart I would like to display (Mon, Tue..etc) respectively on the X-axis. How do I do that?

At the moment I have done:

var ticksTreatment = 'glow';
var xAxisQPerDay = new Rickshaw.Graph.Axis.Time( {
          graph: graphQPerDay,
          ticksTreatment: ticksTreatment
      } );
xAxisQPerDay.render();

but this gives me, of course, the default values 1s, 2s, 3s etc...


Solution

  • Something like this should work:

    var xAxisQPerDay = new Rickshaw.Graph.Axis.X({
        graph: graphQPerDay,
        tickFormat: function(x) {
            switch (x) {
                case 1: return 'Mon';
                case 2: return 'Tue';
                case 3: return 'Wed';
                case 4: return 'Thu';
                case 5: return 'Fri';
                case 6: return 'Sat';
                case 7: return 'Sun';
            }
        }
    });
    
    xAxisQPerDay.render();
    

    A more dynamic approach if you have built a map on the side to cache the field data.

    var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    var xAxisQPerDay = new Rickshaw.Graph.Axis.X({
        graph: graphQPerDay,
        tickFormat: function(x) {
            return days[x];
        }
    });
    
    xAxisQPerDay.render();
    

    OR

    var days = { 0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun' };
    var xAxisQPerDay = new Rickshaw.Graph.Axis.X({
        graph: graphQPerDay,
        tickFormat: function(x) {
            return days[x];
        }
    });
    
    xAxisQPerDay.render();