Search code examples
jqplot

How to make (2) Bar Graph with one overlapping with another one, using JQPlot?


Currently I'm having this code for generating two bars in single graph. But I need to join the two bars (with one overlaps with another). Please help to make code adjustments using JQPlot.

Like in image below, I want the blue graph on the front (which is the array1) the the orange bar (array2) at the back of the blue bar.

enter image description here

  var array1 = ["27", "18", "25", "13", "37", "29", "13", "15", "20"]
  var array2 = ["50", "30", "70", "60", "50", "70", "50", "30", "35"]

        $.jqplot('barChart', [array1, array2], {
            title:'Sales & Marketing',
            animate: true,//!$.jqplot.use_excanvas,
            seriesDefaults:{
                renderer:$.jqplot.BarRenderer,
                pointLabels: { show: true },
                rendererOptions: {
                  showDataLabels: true
                }
            },
            grid: {
                drawGridLines: true,
                gridLineColor: '#A7A7A7',
                background: '#5F5F5F'
            },
            axes: {
                xaxis: {
                    renderer: $.jqplot.CategoryAxisRenderer,
                    ticks: salesPersonsArray,
                    tickOptions: {
                        showGridline: false,
                        show: true
                    },
                    rendererOptions: {
                        drawBaseline: true
                    }
                },
                yaxis: {
                    showTicks : true,
                    min:10,
                    max:100,
                    tickOptions: {
                        showGridline: true
                    },
                    rendererOptions: {
                        drawBaseline: false
                    }
                }
            },            
            highlighter: { show: false }
        });

Thank you for helping.


Solution

  • There is a property stackSeries which can be used with bar charts. This isn't exactly what you want as it puts the each series on top of each other, so using your data you'd end up with the following:

    enter image description here

    Note on the first bar the total is 75 as it's added the 2 bars together (25 + 50) whereas you want the blue bar to be 25 and the yellow bar to be 50.

    To fix this, you can add a function to loop over your 2 series arrays and create a third array which is the difference between the values in array2 and array1

    var array3 = [];
    $.each(array2, function(k, v) {
        // caclulate new value
        array3.push(array2[k] - array1[k]);
    });
    

    then on the graph plot the first series (array1, blue) and the new series (array3, yellow). This will result in what you're after:

    enter image description here

    See this Fiddle for a working demo.