Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Use Chart.js To Display Attractive Charts In A Vue.js Web Application

TwitterFacebookRedditLinkedInHacker News

Charts are a great way to illustrate data within an application. No one likes trying to make sense of raw data or looking at it via a table. Instead a nice bar chart or line graph can paint a perfect picture of what’s going on.

There are a lot of charting libraries available, but my personal favorite is Chart.js. It is a vanilla JavaScript library, so including it within a framework can be a little intimidating.

We’re going to see how to work with Chart.js within a project that uses the Vue.js JavaScript framework.

The image below represents some of the attractive charting that can be done with Chart.js:

There are a lot of possibilities with Chart.js, but everything, more or less, follows the same approach.

Using the Vue CLI to Create a New Vue.js Project

The simplest way to create a Vue.js project is to use the Vue CLI. Rather than trying to work with an existing project and introducing new Chart.js complexity, we’re going to start with a fresh project.

From the CLI, execute the following:

vue init webpack chart-project

When scaffolding a new project, the CLI will ask you a series of questions. We won’t need a router and it doesn’t matter if you choose to include the compiler and runtime or just the runtime. Everything else, use your best judgement.

Downloading Chart.js and the Necessary Project Dependencies

The recommended way to using Chart.js in any project is to install it with the Node Package Manager (NPM). From the CLI, execute the following to install the Chart.js package:

npm install chart.js --save

To focus on charting and not introduce complexity behind requesting remote data, we’re going to mock all our chart data. This means that we won’t need any further dependencies to be successful with our project.

If you wish to extend this example with remote data, check out my previous HTTP tutorial titled, Consume Remote API Data via HTTP in a Vue.js Web Application.

Creating and Managing Charts in the Vue.js Project

In our project we’re not going to focus on routing or anything else. This means that we’ll be spending all of our time in the project’s src/App.vue file.

Open the project’s src/App.vue file and include the following code. We’re going to break it down after.

<template>
    <div id="app">
        <div id="content">
            <canvas ref="chart"></canvas>
        </div>
    </div>
</template>

<script>
    import Chart from 'chart.js';

    export default {
        name: 'app',
        mounted() {
            var chart = this.$refs.chart;
            var ctx = chart.getContext("2d");
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                    datasets: [{
                        label: '# of Votes',
                        data: [12, 19, 3, 5, 2, 3],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255,99,132,1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        }
    }
</script>

<style>
    #app {
        font-family: 'Avenir', Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-align: center;
        color: #2c3e50;
        margin-top: 60px;
    }
    #content {
        margin: auto;
        width: 1024px;
        background-color: #FFFFFF;
        padding: 20px;
    }
</style>

Let’s break down the above file content based on corresponding blocks. Take a look at the <template> block for example:

<template>
    <div id="app">
        <div id="content">
            <canvas ref="chart"></canvas>
        </div>
    </div>
</template>

Chart.js works by making use of the HTML5 canvas. You’ll notice that we don’t have any id or name attribute on the <canvas> element. This is because we don’t plan on interfacing directly with the DOM from our JavaScript. Instead, notice the ref attribute.

With the ref attribute, we can control the HTML element from within Vue.js. This is the correct way to interact with the DOM.

Now let’s look at the <script> block:

<script>
    import Chart from 'chart.js';

    export default {
        name: 'app',
        mounted() {
            var chart = this.$refs.chart;
            var ctx = chart.getContext("2d");
            // Control the chart here
        }
    }
</script>

I’ve removed the part where we make changes to the chart. In the above code we are importing the Chart.js dependency that we had previously downloaded. In the mounted method, we are getting the chart reference that we made in the HTML and getting the context. The mounted method is a lifecycle hook that is called when the application initializes.

When it comes to doing something with the chart, we have the following:

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});

Nothing from the above is specific to Vue.js. In fact, it was taken from the Chart.js documentation.

If you’ve never used Chart.js before, you can have multiple datasets, each with their own configuration and data. The catch is that the data size must match the size of your labels. So in the above example we have six labels and six pieces of data to plot.

Want to add a little more functionality to our chart? Let’s say we want to perform some kind of event any time a data point is clicked.

options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    },
    onClick: (event) => {
        var activePoints = myChart.getElementsAtEventForMode(event, "point", myChart.options);
        if(activePoints.length > 0) {
            var firstPoint = activePoints[0];
            var label = myChart.data.labels[firstPoint._index];
            var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
            alert(label + ": " + value);
        }
    }
}

In the above snippet, we added an onClick method to the chart options. When the chart is clicked, it doesn’t matter where, we capture the point. We only want to perform an action if a data element is clicked. In our situation, we only want to perform an action if a bar is clicked. If this is true, figure out what was clicked and display a simple alert.

Again, this is all JavaScript related and nothing really pertaining to Vue.js specific stuff.

Conclusion

You just saw how to include Chart.js in your Vue.js web application. Most interaction with Chart.js is done purely with JavaScript. Including a chart within your project is as simple as adding a <canvas> element with a Vue.js ref attribute.

Chart.js is a great library for charting. I’ve used it in many projects including an Ionic Framework project back in the day.

The most difficult part of using Chart.js, or any charting library for that matter, is formatting your data. Chart.js expects data for your datasets to be specific. You can massage your data either in your backend or directly in your Vue.js application to make it compatible.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.