Sabbir Ahmed

Sabbir Ahmed

1 month ago

Boost User Engagement with Interactive Charts in JavaScript

Working with charts and graphs has become mandatory now a days for most of the modern web and mobile applications. A graph or chart always works better to understand than numbers from the user’s perspective. There are plenty libraries available in javascript, jquery and react to use graph/chart in your web application. Today we will see how we can integrate beautiful chart in our web application with the help of javascript and jquery. 

Lets jump in


Today we will see a library called Flotcharts. It is very easy to use and has flexibility to customize as required. 

Lets setup the environment for using this library. Lets create a index.html file where we will integrate the CDN from the library:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flot Chart Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flot/dist/es5/jquery.flot.js"></script>
    <style>
        #placeholder {
            width: 600px;
            height: 400px;
        }
    </style>
</head>
<body>
    <h1>My Flot Chart</h1>
    <div id="placeholder"></div>
    <script>
        $(document).ready(function() {
            // Your Flot code will go here
        });
    </script>
</body>
</html>

Here we have taken a div#placeholder which will be used for plotting the graph.

Now we need to add custom data for generating a sample graph. In the script, under $(document).ready(), we can add these data like below: 


$(document).ready(function() {
    var data = [
        [0, 3], [1, 8], [2, 5], [3, 13], [4, 1]
    ];

    $.plot($("#placeholder"), [data], {
        series: {
            lines: {
                show: true
            },
            points: {
                show: true
            }
        },
        grid: {
            hoverable: true,
            clickable: true
        },
        yaxis: {
            min: 0,
            max: 15
        },
        xaxis: {
            min: 0,
            max: 4
        }
    });
});

Lets try to understand the code above:


Data: In the [data] parameter, we are passing the data array. Each element of the data array is holding the X and Y value for graph at that point. For example, [0, 3] means, it will have 3 unit in Y axis at 0 point from X axis. Same for the other elements as well. 

Series Options: Now we are passing lines and points parameters in the series option. 
lines.show indicates to  draw filled lines.
points.show refers to show points on the graph 

Grid Options: hoverable and clickable are enabling interactions to the graph.

Xaxis and yaxis: Set minimum and maximum values for the x and y axes.

Lets enhance the graph a bit more


We can add more options to enhance the graph. There are also other parameters which is very useful to know for further reference. We can add labels, control colors of the graph and much more.

Lets modify our parameters like this: 



$(document).ready(function() {
    var data = [
        { label: "Series 1", data: [[0, 3], [1, 8], [2, 5], [3, 13], [4, 1]] },
        { label: "Series 2", data: [[0, 5], [1, 7], [2, 9], [3, 11], [4, 6]] }
    ];

    $.plot($("#placeholder"), data, {
        series: {
            lines: {
                show: true,
                fill: true,
                fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] }
            },
            points: {
                show: true
            }
        },
        grid: {
            backgroundColor: { colors: ["#fff", "#eee"] },
            borderColor: "#ccc",
            borderWidth: 2,
            hoverable: true,
            clickable: true
        },
        yaxis: {
            min: 0,
            max: 15
        },
        xaxis: {
            min: 0,
            max: 4
        }
    });

    // Tooltip code
    $("<div id='tooltip'></div>").css({
        position: "absolute",
        display: "none",
        border: "1px solid #fdd",
        padding: "2px",
        "background-color": "#fee",
        opacity: 0.80
    }).appendTo("body");

    $("#placeholder").bind("plothover", function (event, pos, item) {
        if (item) {
            var x = item.datapoint[0].toFixed(2),
                y = item.datapoint[1].toFixed(2);

            $("#tooltip").html(item.series.label + " at " + x + " = " + y)
                .css({top: item.pageY+5, left: item.pageX+5})
                .fadeIn(200);
        } else {
            $("#tooltip").hide();
        }
    });
});


Label: you can see we are passing a label name for each of the dataset. These datasets will produce different line in graph for each. And there will be a label for each graph will be shown from this label value. 

Fill and fillColor: for the series.lines, we are making our graph to have a fill color with fill and fillColor parameters to make it more attractive

Grid enhancement: we are also making grids attractive with backgroundColor, borderColor and borderWidth parameters. It will generate a gradient background colors for grids as we have provided 2 colors for backgroundColor in an array. 

Tooltip: we made a custom tooltip element to show the label of the graph in a popup. When you hover over any point of the graph, it will show the label and value in a tooltip element with that. 

Putting it all together


Here is the complete code with putting all the pieces above together: 



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flot Chart Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flot/dist/es5/jquery.flot.js"></script>
    <style>
        #placeholder {
            width: 600px;
            height: 400px;
        }
        #tooltip {
            position: absolute;
            display: none;
            border: 1px solid #fdd;
            padding: 2px;
            background-color: #fee;
            opacity: 0.80;
        }
    </style>
</head>
<body>
    <h1>My Flot Chart</h1>
    <div id="placeholder"></div>
    <script>
        $(document).ready(function() {
            var data = [
                { label: "Series 1", data: [[0, 3], [1, 8], [2, 5], [3, 13], [4, 1]] },
                { label: "Series 2", data: [[0, 5], [1, 7], [2, 9], [3, 11], [4, 6]] }
            ];

            $.plot($("#placeholder"), data, {
                series: {
                    lines: {
                        show: true,
                        fill: true,
                        fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 }] }
                    },
                    points: {
                        show: true
                    }
                },
                grid: {
                    backgroundColor: { colors: ["#fff", "#eee"] },
                    borderColor: "#ccc",
                    borderWidth: 2,
                    hoverable: true,
                    clickable: true
                },
                yaxis: {
                    min: 0,
                    max: 15
                },
                xaxis: {
                    min: 0,
                    max: 4
                }
            });

            $("<div id='tooltip'></div>").appendTo("body");

            $("#placeholder").bind("plothover", function (event, pos, item) {
                if (item) {
                    var x = item.datapoint[0].toFixed(2),
                        y = item.datapoint[1].toFixed(2);

                    $("#tooltip").html(item.series.label + " at " + x + " = " + y)
                        .css({top: item.pageY+5, left: item.pageX+5})
                        .fadeIn(200);
                } else {
                    $("#tooltip").hide();
                }
            });
        });
    </script>
</body>
</html>


And here is a sample chart generated from the code: 



That was a quick example how we can generate a simple chart form this library. But this one has much more flexibility to generate any kind of chart and design. Please have some time to play with it. 

So thats all from this post here. Please give a love to this article if you found this helpful and leave your comments below.

Have a great day.

Comments

Login As User
Word Count: 0