Search code examples
javascriptjquerychartsflot

Flot Bar Chart multiple series issue


I've been using Flot charts for a short period of time and I need to display a bar chart with one or two series depending on the selection:

if (lC2 != 'None') {
      values = [
          { label: lC1, data: arrC1, color: cC1 },
          { label: lC2, data: arrC2, color: cC2 }
               ];
      bWidth = 0.15;
 }
 else {
      values = [{ data: arrC1, color: cC1 }];
      bWidth = 0.3;
}

and my function that draws the chart is:

function BarChartH(id, data, ticksl) {

$.plot(id, data, {
    series:{
        bars: {
            show: true,
            barWidth: bWidth,
            order: 1,
            horizontal: true    
        }
    },
    grid: {
        hoverable: true
        , align: "center"
        //,horizontal: true
    },
    legend: {
        show: true
    }
    , yaxis: { ticks: ticksl }
});
}

But when it needs to display both series (lC2 != 'None') it appears only the second one (the bars become stacked).

The thing is that if I remove 'order:1' from the function and add the order for each data like:

values.push({ label: lC1, bars: { order:1 }, data: arrC1, color: cC1 });
values.push({ label: lC2, bars: { order:2 }, data: arrC2, color: cC2 });

OR

values = [
    { label: lC1, bars: { order:1 }, data: arrC1, color: cC1 },
    { label: lC2, bars: { order:2 }, data: arrC2, color: cC2 }];

it displays both of the series but with a lot of space between the bars and when there are many they overlap (the lC2 bar from the first Y label overlaps with the lC1 bar from the second Y label like in the attached image).

I need to get both the bars of the same Y label closer to make a difference between them, but I don't know what am I doing wrong.

EDIT: Added: fiddle


Solution

  • you have to use this plugin orderBars ... check this fiddle i used the orderBars plugin for that ... also you can increase the value of bWidth to decrease the space between bars.

    also here is what i did:

    var arrC1 = [[7,5], [3,4],[4,3],[6,2],[4,1]];
    var arrC2 = [[2,5], [1,4],[0,3],[5,2],[4,1]];
    
    var ticksl = [[5, "Five"], [4, "Four"], [3, "Three"], [2,"Two"], [1,"One"]];
    
    var data = [{bars:{order:1},data: arrC1,color: 'red'}, 
            {bars:{order:2},data: arrC2,color: 'green'}];
    
    var bWidth=0.43;
    
    $.plot($('#Chart'), data, {
        series: {
            bars: {
                show:true,
                lineWidth: 1,
                barWidth: bWidth,
                order: 1,
                horizontal: true
            }
        },
        grid: {
            align: "center"
        },
        legend: {
            show: true
        },
        yaxis:{
            ticks: ticksl,
            autoscaleMargin: 0.8
        }
    });