DEV Community

Nika
Nika

Posted on • Edited on

Visualization with free JavaScript Libraries: WebDataRocks and ChartJS

Today I'd like to share my experience of creating a powerful data visualization tool by using two free JavaScript libraries.

Mastering data visualization is a crucial skill for your career advancement that is easy to overlook in our fast-paced digital world. The ability to present the data in an understandable form and answer important questions about the business is highly appreciated in any field. As a type of data visualization, data dashboards are incredibly instrumental for communicating insights.

Hopefully, at the end of the tutorial, you'll learn how to power up your project with an interactive and customizable dashboard which helps track specific business metrics.

To complete this tutorial, you only need to have basic JavaScript programming skills.
In case you are eager to see the demo right now, here is the link to it.

Data visualization tools

Let’s start with exploring the functionality of the first tool I’ll be using, namely a pivot table component.

pivot table control

WebDataRocks is a JavaScript pivot table which easily integrates with React, Angular, and AngularJS frameworks. It lets you create reports based on the CSV & JSON data and export them to PDF, Excel or HTML.

The first thing you may notice is the component’s interactiveness: you can add the fields via the field list to compose a report and drag and drop them right on the grid to get a completely new view of the data. Also, it’s possible to drill through the cells to see the raw data, apply filters and sort the records by members or values.

All these features help slice and dice your data with ease. I encourage you to explore the functionality by playing with its demo.

To my mind, this tool is perfect both for developers and the end-users: there are a lot of advanced features available via the JavaScript API and the reporting features accessible from the UI.

What I liked the most is the variety of customization options for all tastes. I've managed to change the component's theme and change the icons of the toolbar.

The second tool is a charting library which you most likely heard of or even used in your projects.

charting library

Chartjs is an open-source JavaScript charting library that integrates with Vue and React with the help of wrappers.

It’s incredibly popular among developers these days and there are reasons for that.
The main features for which ChartJS is loved by developers:

  • It’s lightweight - ships at only 10 KB.
  • Charming visualizations that can spice up any data visualization project.
  • Charts are responsive and work smoothly on any device.
  • Everything is customizable via API - animations, tooltips, legend, and colors. Also, you can control the interaction with each element of the chart.

Another feature I’d like to draw attention to is its brief yet comprehensive documentation. Looking through the articles, I’ve managed to find everything I needed to work with charts. The section about the data structure in each tutorial is especially useful - the information it contains helped me to find out everything about the data format required for certain types of charts.

All in all, whether you are a beginner or a professional developer, it will be easy for you to use ChartJS.

Now let’s head over to practice!

📝 Add WebDataRocks

Install a pivot table by downloading a package into your project or simply by using the WebDataRocks CDN:

<link href="https://cdn.webdatarocks.com/latest/webdatarocks.min.css" rel="stylesheet"> <script src="https://cdn.webdatarocks.com/latest/webdatarocks.toolbar.min.js"></script> <script src="https://cdn.webdatarocks.com/latest/webdatarocks.js"></script>

Create a container where the pivot table should be rendered:

<div id="pivot-table-container"></div>

Define a function which returns the JSON data. I recommend specifying the data types in the first object explicitly:

function getData() {
    return [{
            "Channel": {
                "type": "string"
            },
            "Segment": {
                "type": "string"
            },
            "Profit": {
                "type": "number"
            },
            "Actual Expenses": {
                "type": "number"
            },
            "Budgeted Expenses": {
                "type": "number"
            },
            "Date": {
                "type": "date"
            }
        },
        {
            "Channel": "Other",
            "Segment": "Stores",
            "Profit": 455,
            "Actual Expenses": 250,
            "Budgeted Expenses": 55,
            "Date": "2015-02-14T07:34:08"
        },
        {
            "Channel": "Other",
            "Segment": "Stores",
            "Profit": 156,
            "Actual Expenses": 501,
            "Budgeted Expenses": 55,
            "Date": "2015-02-14T07:34:08"
        }
    ]
}

Initialize the pivot table with some basic configurations, including the data source and container:

var pivot = new WebDataRocks({
    container: "#pivot-table-container",
    toolbar: true,
    report: {
        dataSource: {
            data: getData()
        }
    }
});

📘 Define the slice to show on the grid

As soon as you fill the pivot table with the data, define a slice which is a subset of your data that should be displayed in the report. Put the hierarchies to the rows, columns, and define the measures with suitable aggregations. If you need a composed aggregation, create the calculated value for the measure.

Here is an example of the slice:

"slice": {
    "reportFilters": [{
        "uniqueName": "Date.Month"
    }],
    "rows": [{
            "uniqueName": "Channel"
        },
        {
            "uniqueName": "Segment"
        }
    ],
    "columns": [{
            "uniqueName": "Measures"
        },
        {
            "uniqueName": "Date.Year"
        }
    ],
    "measures": [{
        "uniqueName": "Profit",
        "aggregation": "sum"
    }]
}

🖌️ Highlight important values

If you need to focus on individual values of the report, for example, on the highest and lowest levels of revenue, now is the best time to do it. Apply conditional formatting via the UI.

Or add conditions to the report:

"conditions": [{
        "formula": "#value > 2000",
        "measure": "Profit",
        "format": {
            "backgroundColor": "#66BA5F",
            "color": "#FFFFFF"
        }
    },
    {
        "formula": "#value < 500",
        "measure": "Profit",
        "format": {
            "backgroundColor": "#D32F2F",
            "color": "#FFFFFF"
        }
    }
]

💻 Install ChartJS

The simplest way is to include the library by using its CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></>

Then you need to create two separate containers for the charts:

<canvas id="lineChart"></canvas>
<canvas id="doughnutChart"></canvas>

Don't forget to specify the IDs so as to tell the library where the charts will be rendered.

📊 Initialize charts

To bind the components together, we need to wait until the pivot table is successfully rendered and filled with the data, request this data, pre-process it accordingly to the format required for the line and doughnut charts, and create the charts. In case any changes are applied to the pivot’s report, we need to send the updated data to the charts.

Let’s see how to implement this behaviour.

Define two functions - createLineChart() and createDougnutChart(). To keep things simple, I’ll show how to define one of these functions - the other can be implemented in a similar way.

In createLineChart(), firstly, you need to get the data from the pivot control by using the getData() method which retrieves the data and asynchronously passes it to its callbackHandler and updateHandler. These two handlers define what should happen once the pivot table is created and updated correspondingly. If you want to specify the slice, you can pass it to getData() as a property of the options argument.

function createLineChart() {
    webdatarocks.getData({
        "slice": {
            "rows": [{
                "uniqueName": "Channel",
                "sort": "asc"
            }],
            "columns": [{
                "uniqueName": "Measures"
            }],
            "measures": [{
                "uniqueName": "Profit",
                "aggregation": "sum"
            }]
        },
    }, drawLineChart, updateLineChart);
}

Secondly, you need to define the function which draws the chart and pass it to getData() as callbackHandler.

function drawLineChart(rawData) {
    var data = prepareDataFunction(rawData);
    var data_for_charts = {
        datasets: [{
            data: data.data,
            borderColor: "rgba(193,46,12,1)",
            fill: false,
            backgroundColor: "rgba(193,46,12,1)",
            label: data.label
        }],
        labels: data.labels
    };
    options = {
        responsive: true,
        legend: {
            position: 'right',
        },
        title: {
            display: true,
            fontSize: 18,
            text: 'Profit by Channel'
        },
        scale: {
            ticks: {
                beginAtZero: true
            },
            reverse: false
        },
        animation: {
            animateRotate: false,
            animateScale: true
        }
    };
    var ctx_linechart = document.getElementById("lineChart").getContext("2d");
    line_chart = new Chart(ctx_linechart, {
        data: data_for_charts,
        type: 'line',
        options: options
    });
}

Similarly, define the function which redraws the chart once the report is changed in some way.

function updateLineChart(rawData) {
    line_chart.destroy();
    drawLineChart(rawData);
}

In the demo, you can see the implementation of prepareDataFunction which iterates over the records and prepares the data for the line and doughnut charts.

I’d like to mention that the ability to choose whether to use bezier curves for a line chart or not is cool. It’s known that disabling this functionality improves performance a bit because drawing a straight line is less costly on resources.

🎨 Enjoy the dashboard

As a result, you have a top-notch data dashboard that lets you quickly capture insights and interact with your data - try filtering the data to see how the slice is changed both in the report and on the charts.

You can add it to any project, including React, Angular, and Vue. The reports from the table can be exported to PDF and HTML.
Besides, both components of this dashboard are free which makes them suitable for startups.

Thank you for reading!

I’ll be glad to see your results :)

Play with the demo

See the full code on CodePen 💡

Useful links

About WebDataRocks:

About Chartjs:

Top comments (2)

Collapse
 
papaponmx profile image
Jaime Rios

Hey, Nika. Thanks for sharing!

Collapse
 
veronikaro profile image
Nika

Hi Jaime!

Thank you for your feedback. I'm glad you like the tutorial 🎉

Have a nice day!