Search code examples
javascriptjqueryflot

jQuery flot chart - change labels (ticks) of y-axis


I need to be able to change the labels/ticks of a (horizontal) bar chart based on another array full of labels. - this is part of a name resolver thingy.

So my initalization code looks around the lines of so:

var ticks = [
  ["abc", 0],
  ["def", 1],
  ["ghi", 2],
  ["jkl", 3]
];

//loop for each value goes here
var data = {
  data: [
    [0, 111],
    [1, 222],
    [2, 333],
    [3, 444]
  ], //... etc
  bars: {
    horizontal: true,
    show: true,
    barWidth: 0.8,
    align: "center"
  }
};

var plot = $.plot($("#graph"), data, {
  yaxis: {
    ticks: ticks
  }
  //etc
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://www.flotcharts.org/javascript/jquery.flot.min.js"></script>

<div class="chart" id="graph" style="width:400px;height:300px;"></div>

Is there any way of updating the bar chart without destroying old graph and then creating a new one? - so something like this?:

//New ticks for y-axis
plot.yaxisticks = [["ABC", 0], ["DEF", 1], ["GHI", 2], ["JKL", 3]];
plot.draw();

EDIT:
So I can set the values through plot.getOptions().yaxis.ticks[i][1] = value but it seems like it cannot re-draw the ticks using plot.setupGrid(). Help?


Solution

  • The labels can be changed through plot.getAxes().yaxis.options.ticks, then redrawing the plot.

    function test() {
        var ticks = plot.getAxes().yaxis.options.ticks;
    
        for (var i = 0; i < ticks.length; i++ ){
            ticks[i][1] += " test";
        }
    
        plot.setupGrid();
        plot.draw();
    }
    

    The above code will add " test" to the end of the label.