Search code examples
jquerycodeigniter-3flotjqplot

How to show characters in x axis of flot chart in jquery


I need to use updating chart in plot.js for my project, this is my code:

var data = [],
    totalPoints = 1200,
    $UpdatingChartColors = $("#updating-chart").css('color');

function getRandomData() {
    if (data.length > 0)
        data = data.slice(1);
    while (data.length < totalPoints) {
        var prev = data.length > 0 ? data[data.length - 1] : 50;
        var y = prev + Math.random() * 10 - 5;
        if (y < 0)
            y = 0;
        if (y > 100)
            y = 100;
        data.push(y);
    }
    var res = [];
    for (var i = 0; i < data.length; ++i)
        res.push([i, data[i]])
    return res;
}
var updateInterval = 1500;
$("#updating-chart").val(updateInterval).change(function() {
    var v = $(this).val();
    if (v && !isNaN(+v)) {
        updateInterval = +v;
        $(this).val("" + updateInterval);
    }
});
var options = {
    yaxis: {
        min: 0,
        max: 100
    },
    xaxis: {
        transform: function(v) {
            return -v;
        },
        min: 0,
        max: 90
    },
    colors: [$UpdatingChartColors],
    series: {
        lines: {
            lineWidth: 1,
            fill: true,
            fillColor: {
                colors: [{
                    opacity: 0.4
                }, {
                    opacity: 0
                }]
            },
            steps: false
        }
    }
};

var plot = $.plot($("#updating-chart"), [getRandomData()], options);

I am getting output on x axis like 90, 80, 70, 60, 50, 40, 30, 20, 10, 0. But I need output like D-90, D-80, D-70, D-60, D-50, D-40, D-30, D-20, D-10.

How to achieve that one?


Solution

  • Use the tickFormatter property in your xaxis options:

    tickFormatter: function(val, axis) {
        return 'D-' + val;
    }
    

    See here for a working fiddle and here for more information.

    PS: When using transform you should also specify inverseTransform.