Search code examples
javascriptflot

Set same gap between each point of x axis data in Flot Js


My graph is as below :

enter image description here

I want to make an same gap between each point in flot because I want to show only 6 data at the same time. So I can manage the look of my x axis data. Right now this is not looking good. You can give me another solution for making an x axis label values looking good.


Solution

  • The easiest way to display linear x values in flot is to provide flot with an ascending index then use this index combined with a custom label function to display whatever string you want as the x axis label. The code to do this looks like the following:

    function randomDate() {
        var start = new Date(2012, 01, 01);
        var end = new Date();
        return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
    }
    
    $(function () {
        var theDates = [];
        var dataValues = [];
    
        for (var i = 0; i < 14; i += 0.5) {
            theDates.push(randomDate());
            dataValues.push([i, Math.sin(i)]);    
        }
    
        $.plot($("#placeholder"), [dataValues], {
            xaxis: {
            tickFormatter: function xAxisLabelGenerator(x) {
               return moment(theDates[x]).format('YYYY/MM/DD');
            }
          }
        });
    });
    

    In this example I'm using moment to format a random date and place these in order on the x axis. You'll note that since the dates are completely random they may not even be sequential yet they are all evenly spaced. If you want the fiddle version see here. Best of luck!