Search code examples
jqueryflotstacked-chart

Plotting with Flot: Empty Areas Rendered


Given this HTML (using jquery 3.5.1 and flot 0.8.3):

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Flot Issue</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.min.js"></script>
        <script src="plot.js"></script>
    </head>
    <body>
        <h1>Flot Issue</h1>
        <div id="plot-area" style="width: 800px; height: 400px;"></div>
    </body>
</html>

I'd like to plot some data as a stacked bar (plot.js):

"use strict";

$(function () {

    var graphData = [
        {
            label: "foo",
            data: [ [0, 6], [1, 5], [2, 0] ]
        },
        {
            label: "bar",
            data: [ [0, 3], [1, 0], [2, 8] ]
        },
    ];

    var graphAxis = [ [0, 'First'], [1, 'Second'], [2, 'Third'] ];

    var stack = 0, bars = true, lines = false, steps = false;

    function plot() {
        $.plot($("#plot-area"), graphData, {
            series: {
                stack: stack,
                lines: { show: lines, steps: steps },
                bars: { show: bars, barWidth: 0.6, align: "center" },
            },
            xaxis : {
                ticks: graphAxis,
                autoscaleMargin: 0.02
            },
            yaxis : {
                min: 0,
                tickDecimals: 0,
                minTickSize: 1
            },
            legend : {
                noColumns: 3
            },
            colors: ["#4da74d","#edc240","#afd8f8","#9440ed","#cb4b4b"]
        });
    }

    plot();

});

Plotting does work:

rendered stacked bar plot

However, on the bottom of the "Second" and "Third" bar, the bar is drawn for both categories, even though the area is 0 for one of those. This leads to those empty yellow (Second) and green (Third) borders, which I want to get rid of.

How can I prevent an empty area from being drawn?


Solution

  • You can get Flot to ignore the empty parts by replacing the 0 values with null in your graphData.

    See this fiddle for a full example.