Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
Melissa Zachariadis Avatar asked Jun 22 '15 02:06

Melissa Zachariadis


2 Answers

You can specify ticks array for yaxis.

https://github.com/flot/flot/blob/master/API.md#customizing-the-axes

$(function () {
    
    var ticks = [[0, "abc"], [1, "def"], [2, "ghi"], [3, "jkl"], [4, "four"]];
    var data = [[111, 1], [222, 2], [333, 3],  [444, 4]];
    
    var plot1 = $.plot($("#graph"), [{ data: data, label: "Series A"}], {
    series: {
        legend : {
            show: true
        },
        bars: {
        	horizontal: true,
        	show: true,
        	barWidth: 0.8,
        	align: "center"
    		},
        points : {
            show : true
        }
    },
    yaxis : {
        ticks: ticks
    }
    });
});
<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>
like image 117
Alex Vazhev Avatar answered Oct 26 '22 23:10

Alex Vazhev


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.

like image 42
Melissa Zachariadis Avatar answered Oct 27 '22 00:10

Melissa Zachariadis