Creating Beautiful Charts Using Vue.js Wrappers for Chart.js

Share this article

A maid positioning objects representing different types of chart

Charts are an important part of modern websites and applications. They help to present information that can’t be easily represented in text. Charts also help to make sense of data that would ordinarily not make sense in a textual format by presenting them in a view that’s easy to read and understand.

In this article, I’ll show you how to represent data in the form of various types of chart with the help of Chart.js and Vue.js. Chart.js is a simple yet flexible JavaScript charting library for developers and designers that allows drawing of different kinds of charts by using the HTML5 canvas element. A good refresher on Chart.js can be read here.

Vue.js is a progressive JavaScript framework, which we’ll use alongside Chart.js to demonstrate the chart examples. If you’re new to Vue.js, there’s an awesome primer on using Vue.js on SitePoint. We’ll also be using Vue CLI to scaffold a Vue.js project for the demo we’re going to build.

A maid positioning objects representing different types of chart

Charts, Charts, Charts

There’s an awesome collection of Vue wrappers for various charting libraries on the awesome-vue repo on GitHub. However, as we’re concentrating on Chart.js, we’ll be looking at the following wrappers for that library:

We’ll be using these wrappers to demonstrate how to create different types of charts and also touch on the unique features that each of them offers.

Please note that the source code for this tutorial is available on GitHub.

Scaffolding the Project with Vue CLI

Let’s get started by installing Vue CLI with the following command:

npm install -g @vue/cli

Once that’s done, we can then get started with scaffolding a project by typing:

vue create chart-js-demo

This will open a wizard to walk you through creating a new Vue app. Answer the questions as follows:

? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Linter
? Use history mode for router? Yes
? Pick a linter / formatter config: ESLint with error prevention only
? Pick additional lint features: Lint on save
? Where do you prefer placing config for Babel etc.? In dedicated config files
? Save this as a preset for future projects? No

Now let’s install Chart.js, as well as the various wrappers we need for our app:

cd chart-js-demo
npm install chart.js chartkick hchs-vue-charts vue-chartjs vue-chartkick

Tip: If you use npm 5, there’s no need for the --save flag anymore, as all packages are automatically saved now. Read more about that here.

Let’s test what we have so far and run our application:

npm run serve

If all has gone well, you should be able to open localhost:8080 and see the standard welcome page.

Basic Setup

Next, we’ll need to add a view for each wrapper. Create the following files in src/views:

  • VueChartJS.vue
  • VueChartKick.vue
  • VueCharts.vue
touch src/views/{VueChartJS.vue,VueChartKick.vue,VueCharts.vue}

Then create the following files in src/components:

  • LineChart.vue
  • BarChart.vue
  • BubbleChart.vue
  • Reactive.vue
touch src/components/{LineChart.vue,BarChart.vue,BubbleChart.vue,Reactive.vue}

These correspond to the type of charts we’ll be using.

Finally, you can delete the About.vue file in src/views, the HelloWorld.vue file in src/components, as well as the assets folder in src. We’ll not be needing those.

The contents of your src directory should look like this:

.
├── App.vue
├── components
│   ├── BarChart.vue
│   ├── BubbleChart.vue
│   ├── LineChart.vue
│   └── Reactive.vue
├── main.js
├── router.js
└── views
    ├── Home.vue
    ├── VueChartJS.vue
    ├── VueChartKick.vue
    └── VueCharts.vue

Adding Routes

The next thing we want to do is create the different routes in which we can view the charts for each of the wrappers we created above. We would like to have a /charts route to display charts made with the vue-charts wrapper, /chartjs to display charts made with the vue-chartjs wrapper, and lastly /chartkick to display charts made with the vue-chartkick wrapper. We’ll also leave the / route in place to display the Home view.

Navigate to the src folder of the app and open up therouter.js file. Replace the contents of that file with this:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home'
import VueChartJS from '@/views/VueChartJS'
import VueChartKick from '@/views/VueChartKick'
import VueCharts from '@/views/VueCharts'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/chartjs',
      name: 'VueChartJS',
      component: VueChartJS
    },
    {
      path: '/chartkick',
      name: 'VueChartKick',
      component: VueChartKick
    },
    {
      path: '/charts',
      name: 'VueCharts',
      component: VueCharts
    }
  ]
})

Here we imported the Vue components that we created above. Components are one of the most powerful features of Vue. They help us extend basic HTML elements to encapsulate reusable code. At a high level, components are custom elements that Vue’s compiler attaches behavior to.

Lastly, we defined the routes and components which will serve the different pages we need to display the different charts.

Adding Navigation

We can define our navigation to be used across components in src/App.vue. We’ll also add some basic styling:

<template>
  <div id="app">
    <div id="nav">
      <ul>
        <li><router-link to="/">Home</router-link></li>
        <li><router-link to="/chartjs">vue-chartjs</router-link></li>
        <li><router-link to="/charts">vue-charts</router-link></li>
        <li><router-link to="/chartkick">vue-chartkick</router-link></li>
      </ul>
    </div>
    <router-view />
  </div>
</template>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;
  height: 90px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
  text-decoration: underline;
}

#nav a.router-link-exact-active {
  color: #42b983;
  text-decoration: none;
}

#nav ul {
  list-style-type: none;
  padding: 0;
}

#nav ul li {
  display: inline-block;
  margin: 0 10px;
}

h1 {
  font-size: 1.75em;
}

h2 {
  line-height: 2.5em;
  font-size: 1.25em;
}
</style>

Nothing too revolutionary here. Note the use of the <router-view /> component, which is where we’ll display our views.

Home Component

As mentioned above, the Home component serves as the default (/) route. Open it up and replace the content with the code block below:

<template>
  <section class="hero">
    <div class="hero-body">
      <div class="container">
        <h1>Creating Beautiful Charts Using Vue.js Wrappers For Chart.js</h1>
        <h2>
          Read the article on SitePoint:
          <a href="https://www.sitepoint.com/creating-beautiful-charts-vue-chart-js/">
            Creating Beautiful Charts Using Vue.js Wrappers for Chart.js
          </a>
        </h2>
        <h3>
          Download the repo from GitHub:
          <a href="https://github.com/sitepoint-editors/vue-charts">
            https://github.com/sitepoint-editors/vue-charts
          </a>
        </h3>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'home'
}
</script>

Adding Bulma

One more thing before we start adding charts. Let’s add the Bulma CSS framework to the app. This should make things easier when it comes to CSS.

Open the public/index.html file and add the following inside the head tag:

<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" rel="stylesheet">

Now if you visit localhost:8080, you should be able to navigate around the shell of the app.

Finally we can move on to creating charts!

Making Charts with vue-chartjs

vue-chartjs is a Chart.js wrapper that allows us to easily create reusable chart components. Reusability means we can import the base chart class and extend it to create custom components.

With that being said, we’ll be demonstrating four types of charts that can be built using vue-chartjs: a line chart, a bar chart, a bubble chart, and a bar chart that demonstrates reactivity (the chart updates whenever there’s a change in the data set).

Line Chart

To create a line chart, we’ll create a component to render this type of chart only. Open the LineChart.vue component file inside the src/components folder and add the following code:

<script>
  //Importing Line class from the vue-chartjs wrapper
  import { Line } from 'vue-chartjs'

  //Exporting this so it can be used in other components
  export default {
    extends: Line,
    data () {
      return {
        datacollection: {
          //Data to be represented on x-axis
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              pointBackgroundColor: 'white',
              borderWidth: 1,
              pointBorderColor: '#249EBF',
              //Data to be represented on y-axis
              data: [40, 20, 30, 50, 90, 10, 20, 40, 50, 70, 90, 100]
            }
          ]
        },
        //Chart.js options that controls the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      //renderChart function renders the chart with the datacollection and options object.
      this.renderChart(this.datacollection, this.options)
    }
  }
</script>

Let’s discuss what the code above is doing. The first thing we did was import the chart class we needed (in this case, Line) from the vue-chartjs and exported it.

The data property contains a datacollection object which contains all the information we’ll need to build the line chart. This includes the Chart.js configuration, like labels, which will be represented on the x-axis, the datasets, which will be represented on the y-axis, and the options object, which controls the appearance of the chart.

The mounted function calls renderChart() which renders the chart with the datacollection and options objects passed in as parameters.

Now, let’s open the views/VueChartJS.vue file and add in the following code:

<template>
  <section class="container">
    <h1>Demo examples of vue-chartjs</h1>
    <div class="columns">
      <div class="column">
        <h3>Line Chart</h3>
        <line-chart></line-chart>
      </div>
      <div class="column">
        <h3>Bar Chart</h3>
        <!--Bar Chart example-->
      </div>
    </div>
    <div class="columns">
      <div class="column">
        <h3>Bubble Chart</h3>
        <!--Bubble Chart example-->
      </div>
      <div class="column">
        <h3>Reactivity - Live update upon change in datasets</h3>
        <!--Reactivity Line Chart example-->
      </div>
    </div>
  </section>
</template>

<script>
  import LineChart from '@/components/LineChart'
  import BarChart from '@/components/BarChart'
  import BubbleChart from '@/components/BubbleChart'
  import Reactive from '@/components/Reactive'

  export default {
    name: 'VueChartJS',
    components: {
      LineChart,
      BarChart,
      BubbleChart,
      Reactive
    }
  }
</script>

The VueChartJS.vue file contains the template section which holds the HTML code, a script section which holds the JavaScript code, and a style section which holds the CSS code.

Inside the template section, we used the columns class from Bulma to create a layout that has two columns and two rows. We also added a line-chart component which will be created in the script section.

Inside the script section, we imported the .vue files we created earlier and referenced them in the components object. This means we can then use them in the HTML code like this: line-chart, bar-chart, bubble-chart and reactive.

Now if you navigate to /chartjs, the line chart should display on that page.

See the Pen vue-chart.js – line chart by SitePoint (@SitePoint) on CodePen.

Bar Chart

For the next chart, we’ll create a custom component that helps to render bar charts only. Open the BarChart.vue component file inside the src/components folder and add the following code:

<script>
  //Importing Bar class from the vue-chartjs wrapper
  import { Bar } from 'vue-chartjs'
  //Exporting this so it can be used in other components
  export default {
    extends: Bar,
    data () {
      return {
        datacollection: {
          //Data to be represented on x-axis
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              pointBackgroundColor: 'white',
              borderWidth: 1,
              pointBorderColor: '#249EBF',
              //Data to be represented on y-axis
              data: [40, 20, 30, 50, 90, 10, 20, 40, 50, 70, 90, 100]
            }
          ]
        },
        //Chart.js options that controls the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      //renderChart function renders the chart with the datacollection and options object.
      this.renderChart(this.datacollection, this.options)
    }
  }
</script>

The code above works similarly to the one in the LineChart.vue file. The only difference here is that the Bar class is imported and extended instead of Line.

One more thing: before we can see our bar chart, we need to edit the VueChartJS.vue file and replace <!--Bar Chart example--> with <bar-chart></bar-chart>. We’re simply using the Bar component we created inside in our HTML template.

See the Pen vuechart-js – bar chart by SitePoint (@SitePoint) on CodePen.

Bubble Chart

For the bubble chart, we’ll create a component that helps to render bubble charts only.

Note: bubble charts use bubbles/circles to display data in a three dimension method (x, y, r). x is used to display the horizontal axis data, y is used to display the vertical data, and r is used to display the size of the individual bubbles.

Open the BubbleChart.vue component file inside the src/components folder and add the following code:

<script>
  //Importing Bubble class from the vue-chartjs wrapper
  import { Bubble } from 'vue-chartjs'
  //Exporting this so it can be used in other components
  export default {
    extends: Bubble,
    data () {
      return {
        datacollection: {
          //Data to be represented on x-axis
          labels: ['Data'],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              pointBackgroundColor: 'white',
              borderWidth: 1,
              pointBorderColor: '#249EBF',
              //Data to be represented on y-axis
              data: [
                {
                  x: 100,
                  y: 0,
                  r: 10
                },
                {
                  x: 60,
                  y: 30,
                  r: 20
                },
                {
                  x: 40,
                  y: 60,
                  r: 25
                },
                {
                  x: 80,
                  y: 80,
                  r: 50
                },
                {
                  x: 20,
                  y: 30,
                  r: 25
                },
                {
                  x: 0,
                  y: 100,
                  r: 5
                }
              ]
            }
          ]
        },
        //Chart.js options that controls the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      //renderChart function renders the chart with the datacollection and options object.
      this.renderChart(this.datacollection, this.options)
    }
  }
</script>

The code above works similarly to the code in the LineChart.vue and BarChart.vue files. The difference here is that the Bubble class is imported and extended instead of Line or Bar and the datasets object takes in different values for x, y and z.

We need to do one more thing before we can see our bubble chart — the same thing we did for other charts: edit the VueChartJS.vue file and replace <!--Bubble Chart example--> with <bubble-chart></bubble-chart>.

See the Pen vue-chartjs – bubble chart by SitePoint (@SitePoint) on CodePen.

Bar Chart That Demonstrates Reactivity

The last example we’ll be demonstrating with vue-chartjs is how it can be used to make a chart that automatically updates whenever there’s a change in the data set. It’s important to note that Chart.js ordinarily doesn’t offer this feature, but vue-chartjs does — with the help of either of these two mixins:

  • reactiveProp
  • reactiveData

Open the Reactive.vue component file inside the src/components folder and type in the following code:

<script>
  //Importing Bar and mixins class from the vue-chartjs wrapper
  import { Bar, mixins } from 'vue-chartjs'
  //Getting the reactiveProp mixin from the mixins module.
  const { reactiveProp } = mixins
  export default Bar.extend({
    mixins: [ reactiveProp ],
    data () {
      return {
        //Chart.js options that control the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      // this.chartData is created in the mixin and contains all the data needed to build the chart.
      this.renderChart(this.chartData, this.options)
    }
  })
</script>

The first thing we did in the code above was to import the Bar and mixins classed from the vue-chartjs wrapper and extend Bar. We also extracted the reactiveProp mixin from the mixins module to be used for reactivity.

The reactiveProp mixin extends the logic of your chart component, automatically creates a prop named chartData, and adds a Vue watcher to this prop. We didn’t create a dataset object this time, as all the data needed will be inside the chartData prop.

For this to work, we’ll need to edit our VueChartJS.vue even further. Open VueChartJS.vue, and after the components property, add the following code:

data () {
  return {
    // instantiating datacollection with null
    datacollection: null
  }
},
created () {
  //anytime the vue instance is created, call the fillData() function.
  this.fillData()
},
methods: {
  fillData () {
    this.datacollection = {
      // Data for the y-axis of the chart
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#f87979',
          // Data for the x-axis of the chart
          data: [this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt()]
        }
      ]
    }
  },
  getRandomInt () {
    // JS function to generate numbers to be used for the chart
    return Math.floor(Math.random() * (50 - 5 + 1)) + 5
  }
}

Let’s go through the code above. In the data object we return datacollection, which is set to null, and in the created method, we call fillData() anytime the component instance is created. The fillData function will be created in the methods object.

In the methods object, we create a function called fillData. This function creates a datacollection object, which contains a label array (data for the x-axis), and a datasets array, which holds the data array needed for the y-axis.

Note: the content of the data array is a getRandomInt function, which generates a random number for us.

Finally, to display our chart and see if reactivity works, replace <!--Reactivity Line Chart example--> with this:

<reactive :chart-data="datacollection"></reactive>
<button class="button is-primary" @click="fillData()">Randomize</button>

We’re using the reactive component we created and passing the contents of datacollection to the chart-data props to display the chart. And we also have a button that calls the fillData() method any time it’s clicked on.

Navigate to /chartjs route in the app to see the new chart and click on the Randomize button to see the chart automatically render again with the new data in real time.

See the Pen vue-chartjs – reactive bar chart by SitePoint (@SitePoint) on CodePen.

Making Charts with vue-charts

vue-charts takes a very different approach to building charts from vue-chartjs. It doesn’t require you to create separate components to process data and render the chart. All data required for the chart can be instantiated in the Vue instance like this:

data () {
  return {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    dataset: [65, 59, 80, 81, 56, 55, 40]
  }
}

And we can easily display a line chart by using <chartjs-line></chartjs-line> in our template, a bar chart by using <chartjs-bar></chartjs-bar>, and a radar chart by using <chartjs-radar></chartjs-radar>.

Before we go on, we need to register vue-charts globally. Open the main.js inside the src folder and add the following lines of code under the existing import statements:

import 'chart.js'
import 'hchs-vue-charts'

Vue.use(window.VueCharts)

Here we import the Chart.js library and hchs-vue-charts wrapper from the node_modules folder and register it globally with Vue.use(window.VueCharts).

Now let’s get started with vue-charts. Open up the VueCharts.vue file we created earlier and type in the following code:

<template>
  <section class="container">
    <h1>Demo examples of vue-charts</h1>
    <div class="columns">
      <div class="column">
        <h3>Line Chart</h3>
        <!--Line Chart Example-->
      </div>
      <div class="column">
        <h3>Bar Chart</h3>
        <!--Bar Chart Example-->
      </div>
    </div>
    <div class="columns">
      <div class="column">
        <h3>Radar Chart</h3>
        <!--Radar Chart Example-->
      </div>
      <div class="column">
        <h3>Data Binding Line Chart</h3>
        <!--Data Binding Line Chart Example-->
      </div>
    </div>
  </section>
</template>

<script>
  export default {
    name: 'VueCharts',
    data () {
      return {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        dataset: [65, 59, 80, 81, 56, 55, 40]
      }
    }
  }
</script>

In the code block above we created placeholders for charts, and all we have to do is start putting them in.

We then added the labels and data we’ll be using for the various charts in the data object inside the script section.

Let’s begin to create the charts now.

Line Chart

To add the line chart, all we have to is add <chartjs-line></chartjs-line> in place of the comment <!--Line Chart Example--> in the template section of the VueCharts.vue file. We don’t need to import any component because vue-charts has been declared globally in main.js.

Bar Chart

We do the same for bar charts. Add <chartjs-bar></chartjs-bar> in place of the comment <!--Bar Chart Example--> in the template section of the VueCharts.vue file.

Radar Chart

We do the same for radar charts. Add <chartjs-radar></chartjs-radar> in place of the comment <!--Radar Chart Example--> in the template section of the VueCharts.vue file.

Once that’s done, you can navigate to /charts and check out the charts we just created.

See the Pen vue-charts demo by SitePoint (@SitePoint) on CodePen.

A Data Binding Example with a Line Chart

Data binding in vue-charts is similar to that of vue-chartjs, although vue-charts automatically updates the chart whenever the data set changes.

To test this, we’ll create a function named addData and add it to the methods object of the component:

methods: {
  addData () {
    this.dataset.push(this.dataentry)
    this.labels.push(this.datalabel)
    this.datalabel = ''
    this.dataentry = ''
  }
}

The addData method pushes the current value of the data form input and label form input (which we’ll be adding soon) to the current data set. Now let’s add the component as well as the form to add new data and a label.

Add the following piece of code in place of the comment <!--Data Binding Line Chart Example-->:

<form @submit.prevent="addData">
  <input placeholder="Add a Data" v-model="dataentry">
  <input placeholder="Add a Label" v-model="datalabel">
  <button type="submit">Submit</button>
</form>
<chartjs-line :labels="labels" :data="dataset" :bind="true"></chartjs-line>

The code above is a form that allows you to type in values of data and label and then submit the form. The chart will render automatically with the latest entry.

See the Pen vue-charts data binding by SitePoint (@SitePoint) on CodePen.

Making Charts with vue-chartkick

vue-chartkick is a Vue wrapper that allows you to create beautiful charts with one line. We’ll be demonstrating the use of this library with four examples. We’ll be creating a line chart, bar chart, scatter chart and also use the download feature (downloadable charts).

In terms of handling data needed for the chart data set, vue-chartkick gives us two options. We can do something like <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart>, in which the data is added inline, or <line-chart :data="chartData"></line-chart>, and we declare the chartData array in the Vue data object like this:

data () {
  return {
    chartData: [['Jan', 44], ['Feb', 27], ['Mar', 60], ['Apr', 55], ['May', 37], ['Jun', 40], ['Jul', 69], ['Aug', 33], ['Sept', 76], ['Oct', 90], ['Nov', 34], ['Dec', 22]]
  }
}

Let’s get started with using vue-chartkick. Before we go on, open the main.js file inside the src folder and add the following code:

import Chartkick from 'chartkick'
import VueChartkick from 'vue-chartkick'

Vue.use(VueChartkick, { Chartkick })

Here we import the Chartkick library and the vue-chartkick wrapper from node_modules and register it globally with Vue.use(VueChartkick, { Chartkick }).

To start creating charts with vue-chartkick, open up the VueChartKick.vue file we created earlier and add the following code:

<template>
  <section class="container">
    <h1>Demo examples of vue-chartkick</h1>
    <div class="columns">
      <div class="column">
        <h3>Line Chart</h3>
        <!--Line Chart example-->
      </div>
      <div class="column">
        <h3>Bar Chart</h3>
        <!--Bar Chart example-->
      </div>
    </div>
    <div class="columns">
      <div class="column">
        <h3>Scatter Chart</h3>
        <!--Scatter chart example-->
      </div>
      <div class="column">
        <h3>Downloadable Line Chart</h3>
        <!--Downloadable line chart-->
      </div>
    </div>
  </section>
</template>

<script>
  export default {
    name: 'VueChartKick',
    data () {
      return {
        chartData: [['Jan', 44], ['Feb', 27], ['Mar', 60], ['Apr', 55], ['May', 37], ['Jun', 40], ['Jul', 69], ['Aug', 33], ['Sept', 76], ['Oct', 90], ['Nov', 34], ['Dec', 22]]
      }
    }
  }
</script>

In the code block above, we again created placeholders for the different types of charts we’ll be creating, and all we have to do is start putting them in.

We then created the chartData array that holds data we’ll be using for the various charts in the data object inside the script section. Let’s begin to create the charts now.

Line Chart

Creating a line chart with vue-chartkick is very simple and straightforward. All you have to do is bring in the vue-chartkick line-chart component and also determine what dataset you want to use — something like this: <line-chart :data="chartData"></line-chart>. In this case, the data prop is set to the chartData array in the Vue data object.

Therefore, replace the comment <!--Line Chart example--> inside the VueChartKick.vue file with <line-chart :data="chartData"></line-chart> and the line chart should display nicely now.

Bar Chart

We can create a bar chart in the same way we created the line chart above. But in this case, we’ll try something different. Instead of using the chartData array as the data set, we’ll add the data set inside the props, like this: <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart>.

Replace the comment <!--Bar Chart example--> inside the VueChartKick.vue file with <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart>, and your bar chart should display now.

Scatter Chart

Scatter charts also work like the line and bar charts above. Replace the comment <!--Scatter Chart example--> inside the VueChartKick.vue file with <scatter-chart :data="[[174.0, 80.0], [176.5, 82.3], [180.3, 73.6]]"></scatter-chart> and your scatter chart should display now.

Downloading a Chart

vue-chartkick has a pretty neat feature that vue-chartjs and vue-charts lack: the ability to create downloadable charts. Once a chart has been set to downloadable, users can easily save the chart as an image. So how does this work? Let’s check it out with a line chart:

<line-chart :data="chartData" :download="true"></line-chart>

We set the :download prop to true, and that means the chart is downloadable. That’s all!

Replace the comment <!--Downloadable line chart--> inside the VueChartKick.vue file with <line-chart :data="chartData" :download="true"></line-chart> to see and test the download feature on your app. You can hover over the new chart to see the download button.

Demo

See the Pen vue-chartkick demos by SitePoint (@SitePoint) on CodePen.

Comparisons

So now that we’ve gone through the three Vue.js wrappers for Chart.js, what are the pros and cons of each?

vue-chartjs

vue-chartjs is perhaps the most powerful of the three wrappers. It gives so much room for flexibility and also ships with a reactivity feature (the ability to re-render a chart automatically if there’s been a change in the data).

A con for the wrapper would be that configuring the chart can be somewhat complex at the beginning, due to the various options available, and also because you have to create an external file to hold the configuration for the wrapper.

vue-charts

vue-chartjs is a pretty good Chart.js wrapper. It’s very easy to set up, unlike vue-chartjs. It doesn’t require you to create separate components to process data and render charts. All the data required for the chart can be instantiated in the Vue instance, as seen in the examples above. It also ships with a reactivity feature (the ability to render a chart automatically if there’s been a change in the data set) without a need for mixins.

vue-chartkick

vue-chartkick is also a pretty good Chart.js wrapper. It may be the wrapper with the easiest path to usage among the three Chart.js wrappers.

The data set for the chart can be added in two different ways in vue-chartkick. We can do something like <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart>, in which the data is added inline, or <line-chart :data="chartData"></line-chart>, and we declare the chartData array in the Vue data object as seen above in the examples. It also ships with an awesome feature that allows you to download your charts as an image — something that the other wrappers lack.

The only disadvantage of vue-chartkick is that it doesn’t support reactivity out of the box.

Conclusion

In this article, I introduced various Vue wrappers for Chart.js, and also demonstrated examples of how to use each of them to create beautiful charts for your next web project.

The source code for this tutorial is available on GitHub, and if you’d like to see a live demo of the tutorial, you can also see that here.

Frequently Asked Questions (FAQs) about Creating Beautiful Charts with Vue and Chart.js

How Can I Customize the Appearance of My Charts in Vue and Chart.js?

Customizing the appearance of your charts in Vue and Chart.js is quite straightforward. You can modify the colors, labels, tooltips, and even animations. For instance, to change the color of your chart, you can modify the ‘backgroundColor’ property in your dataset. You can also customize the labels by modifying the ‘labels’ array in your data object. Tooltips can be customized in the options object, and animations can be modified in the ‘animation’ property of the options object. Remember, customization is key to making your charts more engaging and easier to understand.

Can I Use Vue and Chart.js to Create Real-Time Charts?

Yes, you can create real-time charts using Vue and Chart.js. This can be achieved by using the ‘reactiveProp’ mixin provided by Vue-chartjs. This mixin makes your chart reactive to changes in its parent component’s data. Therefore, whenever the data changes, your chart will automatically update to reflect these changes. This feature is particularly useful when dealing with data that changes frequently, such as stock prices or sensor readings.

How Can I Add Interactivity to My Charts?

Adding interactivity to your charts can greatly enhance the user experience. Vue and Chart.js provide several options for adding interactivity. For instance, you can add ‘onClick’ events to your chart elements. This allows you to execute a function whenever a user clicks on a chart element. You can also use tooltips to display additional information when a user hovers over a chart element.

Can I Use Vue and Chart.js to Create Complex Charts?

Absolutely. Vue and Chart.js support a wide range of chart types, including line, bar, pie, doughnut, radar, and polar area charts. You can also create complex charts by combining multiple chart types. For instance, you can create a combo chart that combines a line chart and a bar chart. This allows you to display different types of data on the same chart, making it easier for users to compare and analyze the data.

How Can I Optimize the Performance of My Charts?

Optimizing the performance of your charts is crucial, especially when dealing with large datasets. Vue and Chart.js provide several options for performance optimization. For instance, you can use the ‘lazy’ mode to delay the rendering of your chart until it becomes visible on the screen. You can also use the ‘destroy’ method to remove a chart when it’s no longer needed. This frees up memory and improves the overall performance of your application.

How Can I Export My Charts as Images?

Vue and Chart.js allow you to export your charts as images. This can be done using the ‘toBase64Image’ method, which returns a Base64 encoded string representing the chart. You can then use this string to create an image file. This feature is particularly useful when you need to share your charts or include them in reports or presentations.

Can I Use Vue and Chart.js with Other Libraries or Frameworks?

Yes, Vue and Chart.js can be used with other libraries or frameworks. For instance, you can use Vue and Chart.js with Vuex for state management, or with Vue Router for routing. You can also use Vue and Chart.js with other UI libraries, such as Vuetify or BootstrapVue, to create beautiful and responsive charts.

How Can I Debug My Charts in Vue and Chart.js?

Debugging your charts in Vue and Chart.js can be done using the browser’s developer tools. For instance, you can use the console to log errors or warnings, or the debugger to step through your code. You can also use Vue’s devtools extension, which provides a set of tools specifically designed for debugging Vue applications.

Can I Use Vue and Chart.js to Create Mobile-Friendly Charts?

Yes, Vue and Chart.js support responsive design, which means your charts will automatically adjust to fit different screen sizes. This can be achieved by setting the ‘responsive’ property to true in your chart options. You can also use the ‘maintainAspectRatio’ property to control how your chart scales when the aspect ratio changes.

How Can I Animate My Charts in Vue and Chart.js?

Animating your charts can make them more engaging and easier to understand. Vue and Chart.js provide several options for animation. For instance, you can use the ‘animation’ property in your chart options to control the duration, easing, and other aspects of the animation. You can also use the ‘animate’ method to animate specific changes to your chart.

Yomi EluwandeYomi Eluwande
View Author

I'm a 21 year-old freelance front-end developer who cares about design. I studied Computer Engineering in school. I currently work at Anakle as a Software Developer.

Chart.jsnilsonjvuevue-hubvue-tutorialsvue.js
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week