django
django

Reputation: 2909

jQuery Flot Chart add label per series

I am using http://www.flotcharts.org/ library to draw 2 connected series. I can create Graph successfuly, you can see my JSFIDDLE below.

To do: The problem is I want to add one label to the top-center of each series. And I want to add label in such a way that if graph is resized it stays at top-center of series. How can I do that ?

IMAGE:

enter image description here

JSFIDDLE: http://jsfiddle.net/bababalcksheep/ktZ5X/2/

HTML/CSS:

html, body {height: 100%; }

JS:

var options = {
    series: {
        lines:  { show: true,lineWidth: 2,fill: true},
        points: { show: true,radius: 3,lineWidth: 1},
        shadowSize: 2
    },
    legend: { show: false}
};

var DATA = [{
    "label": "Group-1",
        "data": [
        [0.25, 0.25],
        [0.5, 0.5],
        [0.875, 0.875],
        [1, 1]
    ]
}, {
    "label": "Group-2",
        "data": [
        [1, 0.5],
        [1.25, 0.25],
        [1.5, 0.5],
        [1.88, 0.875],
        [2, 1]
    ]
}];
var plot = $.plot("#placeholder", DATA, options);

Upvotes: 2

Views: 1937

Answers (2)

Mark
Mark

Reputation: 108512

I agree with @iLikePrograms adding it in a hook event is the best approach. Here's an updated fiddle.

In your options add:

hooks: { drawSeries : [addLabel] }

Where the addLabel function is:

addLabel = function(plot, ctx, series){
    var xaxis = series.xaxis;
    var yaxis = series.yaxis;
    // space midway on series
    var x = (series.data[series.data.length-1][0] + series.data[0][0])/2;
    // just below top of plot
    var y = yaxis.max - (yaxis.tickSize / 2);
    ctx.font = "16px 'Segoe UI'";
    ctx.fillStyle = "black";
    var text = series.label;
    ctx.fillText(text, xaxis.p2c(x), yaxis.p2c(y)); // add the label
} 

Upvotes: 3

Raidri
Raidri

Reputation: 17550

You can use the comments plugin for that. See this updated fiddle for a start.

New options:

    comment: {
        show: true
    },
    comments: [{
        x: 0.625,
        y: 1,
        contents: "Group-1"
    }, {
        x: 1.5,
        y: 1,
        contents: "Group-2"
    }]

Upvotes: 1

Related Questions