Flot With "String" x-axis
Asked Answered
D

3

53

When using flot I would like to have a string based x-axis. For example I have a list of customers "Bob", "Chris", "Joe" and would like to plot their revenue on the Y-Axis. (this is a bar graph)

It seems at first glance flot only supports numeric types on the x-axis. Is this true?

Donnadonnamarie answered 28/4, 2011 at 15:19 Comment(0)
A
87

@Matt is close, but it would make more sense to just use the ticks option to directly specify what ticks should have what labels:

var options = {

...
  xaxis: {
    ticks: [[0,'Bob'],[1,'Chris'],[2,'Joe']]
  }
...

};

EDIT: it looks like this (I added more data than labels, but you get the idea).

Anticlimax answered 28/4, 2011 at 16:7 Comment(2)
There's also a "categories" plugin : flotcharts.org/flot/examples/categories – but I haven't been able to have proper labels on the x axis for now :/Mallet
@Aheho - thanks, I updated it to point to a source of flot that actually exists :)Anticlimax
L
18

You should be able to do this using the tickFormatter option as per this question. I haven't tried it myself, but give this a shot:

var xAxisLabels = ['Bob', 'Chris', 'Joe'];    
function xAxisLabelGenerator(x){
    return xAxisLabels[x];
}

var plot = $.plot($("#placeholder"), { 
    // snip other options...
    xaxis: {
       transform: xAxisLabelGenerator,
       tickFormatter: xAxisLabelGenerator 
    }
});

This means that the actual x-values should be 0, 1, 2, ...

Lexy answered 28/4, 2011 at 15:33 Comment(5)
+1 - It may not have been the chosen answer (which I also upvoted) but this is very useful.Dobson
the x parameter on your label generator, where does that come from?Haydenhaydn
@KasperSkov flot passes the parameter to the callback you specify.Lexy
Really? That makes no sense to me :) I would think you would have to do something like transform:function (x) { return xAxisLabelGenerator(x); }Haydenhaydn
@KasperSkov transform:function (x) { return xAxisLabelGenerator(x); } is an unnecessarily verbose, though equivalent, way of writing what's in my answer: transform: xAxisLabelGenerator.Lexy
B
18

The Categories plugin (jquery.flot.categories.js) will do this quite nicely, so that data can be formatted like this:

var data = [ ["January", 10], ["February", 8], ["March", 4], ["April", 13], ["May", 17], ["June", 9] ];

and plot like this: enter image description here

See: http://www.flotcharts.org/flot/examples/categories/index.html

Bettiebettina answered 19/12, 2013 at 16:27 Comment(1)
Worked like a charm!Heterolysis

© 2022 - 2024 — McMap. All rights reserved.