How to make Flot bar chart

Bar chart is often used to compare relations of different data groups, the greater the length of bar, the bigger the value. There is also a horizontal bar chart, the difference between bar chart and horizontal bar chart is bars.horizontal, if it`s set to ture, the chart will be displayed as horizontal bar chart.

This chapter shows you how to make a vertical bar chart and horizontal bar chart. Making a bar chart is not so different from making a line chart, if you have read the last chapter line chart, you can get started easily in this chapter.

Bar chart example

Making a bar chart

In this example, we use average temperature of world cities in 2012 as data source, to make this example simplier, we only take six cities data.

First, insert the palceholder into the page, and specify it`s id as well as the length and width.
   
        <div id="flot-placeholder" style="width:400px;height:300px"></div>
        
The next step is to create the data, the data we need is slightly different between bar chart and line chart, usually bar charts are used for comparing relations of different data groups, so in here we added 6 array data, it represents average temperature of 6 cities separately, and in this example we didn`t use time series data, so we use serial number in x axis, y axis use temperature. Finally, we put those array datas into dataset variable, and sepcify label with "2012 Average Temperature", we also use color attribute to set bar color to "#5482FF". If you have multiple data sets, to specify different colors to each data set could help to improve user experience.
   
        var data = [    
            [0, 11], //London, UK
            [1, 15], //New York, USA
            [2, 25], //New Delhi, India
            [3, 24], //Taipei, Taiwan
            [4, 13], //Beijing, China
            [5, 18]  //Sydney, AU
        ];

        var dataset = [
            { label: "2012 Average Temperature", data: data, color: "#5482FF" }
        ];
        
Because we are not using time series data for x axis, so tick labels of x axis will only show 0, 1, 2, ..., so we will create our own ticks labels, first, create an array call "ticks",  and specify data of x axis with serial number starting from 0, as for y axis, we put in the value that will be shown in the label, in here we put in the name of cities.

After finished with ticks array, we can assign ticks to xaxis.ticks, this way, tick labels of x axis will show the name of cities. You can also create your own tick labels for y axis by setting value to yaxis.ticks.
   
        var ticks = [
            [0, "London"], [1, "New York"], [2, "New Delhi"], [3, "Taipei"], [4, "Beijing"], [5, "Sydney"]
        ];

        xaxis: {           
          ticks: ticks
        }
        
If you`re making bar charts, remember to set series.bars.show with true value in the options, it will come out as bar chart, otherwise it will come out as line chart by default. And we use bars.align to specify whether a bar should be right-aligned, left-aligend or centered. If you want to the width of a bar, you can use bars.barWidth, barWidth is the width of the bars in units of the x axis , not in pixels, in here we set it to 0.5.
             series: {
                bars: {
                    show: true
                }
            },
            bars: {
                align: "center",
                barWidth: 0.5
            }
        
We metioned how to create your own tick labels above, but what if you want to add unit like °C or $ to tick labels of y axis, Flot has a function call tickFormatter, the function is passed tow parameters, the tick value and an axis object, and will return a string, we can take advantage of this function. Below is how we add °C to tick labels of y axis.
   
        yaxis: {                
            tickFormatter: function (v, axis) {
                return v + "°C";
            }
        }        
        
In this example we also use the axisLabel plugin, we`ve already explained how it works in How to make Flot line chart.
   
        xaxis: {
            axisLabel: "World Cities",
            axisLabelUseCanvas: true,
            axisLabelFontSizePixels: 12,
            axisLabelFontFamily: 'Verdana, Arial',
            axisLabelPadding: 10
        }

        yaxis: {
            axisLabel: "Average Temperature",
            axisLabelUseCanvas: true,
            axisLabelFontSizePixels: 12,
            axisLabelFontFamily: 'Verdana, Arial',
            axisLabelPadding: 3
        }
        
In the end, we can call $.plot, and specify placeholder, and pass dataset and options into it, then the drawing is complete. In the next chapter we will talk about how to make a horizontal bar chart, bar chart and horizontal bar chart not so different from each other, except you need to swap data of x axis with y axis.
   
        $(document).ready(function () {
            $.plot($("#flot-placeholder"), dataset, options);    
        });
        

Complete code of this chapter

   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="/js/lib/jquery-1.8.3.min.js" type='text/javascript'></script>  
    <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="/js/flot/excanvas.min.js"></script><![endif]-->
    
    <script type="text/javascript" src="/js/flot/jquery.flot.min.js"></script>    
    <script type="text/javascript" src="/js/flot/jquery.flot.symbol.js"></script>
    <script type="text/javascript" src="/js/flot/jquery.flot.axislabels.js"></script>
    
    <script type="text/javascript">
        //******* 2012 Average Temperature - BAR CHART
        var data = [[0, 11],[1, 15],[2, 25],[3, 24],[4, 13],[5, 18]];
        var dataset = [{ label: "2012 Average Temperature", data: data, color: "#5482FF" }];
        var ticks = [[0, "London"], [1, "New York"], [2, "New Delhi"], [3, "Taipei"],[4, "Beijing"], [5, "Sydney"]];

        var options = {
            series: {
                bars: {
                    show: true
                }
            },
            bars: {
                align: "center",
                barWidth: 0.5
            },
            xaxis: {
                axisLabel: "World Cities",
                axisLabelUseCanvas: true,
                axisLabelFontSizePixels: 12,
                axisLabelFontFamily: 'Verdana, Arial',
                axisLabelPadding: 10,
                ticks: ticks
            },
            yaxis: {
                axisLabel: "Average Temperature",
                axisLabelUseCanvas: true,
                axisLabelFontSizePixels: 12,
                axisLabelFontFamily: 'Verdana, Arial',
                axisLabelPadding: 3,
                tickFormatter: function (v, axis) {
                    return v + "°C";
                }
            },
            legend: {
                noColumns: 0,
                labelBoxBorderColor: "#000000",
                position: "nw"
            },
            grid: {
                hoverable: true,
                borderWidth: 2,
                backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
            }
        };

        $(document).ready(function () {
            $.plot($("#flot-placeholder"), dataset, options);
            $("#flot-placeholder").UseTooltip();
        });

        function gd(year, month, day) {
            return new Date(year, month, day).getTime();
        }

        var previousPoint = null, previousLabel = null;

        $.fn.UseTooltip = function () {
            $(this).bind("plothover", function (event, pos, item) {
                if (item) {
                    if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
                        previousPoint = item.dataIndex;
                        previousLabel = item.series.label;
                        $("#tooltip").remove();

                        var x = item.datapoint[0];
                        var y = item.datapoint[1];

                        var color = item.series.color;

                        //console.log(item.series.xaxis.ticks[x].label);                

                        showTooltip(item.pageX,
                        item.pageY,
                        color,
                        "<strong>" + item.series.label + "</strong><br>" + item.series.xaxis.ticks[x].label + " : <strong>" + y + "</strong> °C");
                    }
                } else {
                    $("#tooltip").remove();
                    previousPoint = null;
                }
            });
        };

        function showTooltip(x, y, color, contents) {
            $('<div id="tooltip">' + contents + '</div>').css({
                position: 'absolute',
                display: 'none',
                top: y - 40,
                left: x - 120,
                border: '2px solid ' + color,
                padding: '3px',
                'font-size': '9px',
                'border-radius': '5px',
                'background-color': '#fff',
                'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
                opacity: 0.9
            }).appendTo("body").fadeIn(200);
        }
    </script>
</head>
<body>
    <div style="width:450px;height:300px;text-align:center;margin:10px">        
        <div id="flot-placeholder" style="width:100%;height:100%;"></div>        
    </div>
</body>
</html>
        


Practice

You can find the source code of this example and test it online! Go to Example Tester