Tutorial

How To Use Chart.js with Vue.js

Vue.js

Introduction

Chart.js is a powerful way to create clean graphs with the HTML5 <canvas> element. With Vue’s data() object, it is possible to store data and manipulate it to change graphs when needed.

In this article, you will use Chart.js in a sample Vue project to display information about planets in the solar system.

Prerequisites

To complete this tutorial, you will need:

This tutorial was verified with Node v15.11.0, npm v7.6.1, vue v2.6.11, and Chart.js v2.9.4.

Step 1 — Setting Up the Project

To quickly set up the project, this article will recommend using @vue/cli.

Note: This article will take the approach of using npx to avoid a global installation of @vue/cli;

  • npx @vue/cli create vue-chartjs-example --default

Navigate to the newly created project directory;

  • cd vue-async-computed-example

Chart.js can be installed through npm with the following command:

  • npm install chart.js@2.9.4

At this point, you will have a new Vue project that supports Chart.js.

Step 2 — Creating the Chart Component

This chart will consist of two datasets:

  1. The number of moons each planet in the solar system has.
  2. The mass of each planet in the solar system.

With these two datasets, we can have different chart types to show correlations in data.

Open your code editor and under src directory and components subdirectory, create a new PlanetChart.vue file.

Every Chart.js chart needs to have a <canvas> in the HTML markup. The id of the chart is used as a selector to bind the JavaScript to it.

PlanetChart.vue
<template>
  <div>
    <canvas id="planet-chart"></canvas>
  </div>
</template>

<script>
import Chart from 'chart.js'

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

Next, you will modify the App.vue file to use the new PlanetChart:

src/App.vue
<template>
  <div id="app">
    <PlanetChart/>
  </div>
</template>

<script>
import PlanetChart from './components/PlanetChart.vue'

export default {
  name: 'App',
  components: {
    PlanetChart
  }
}
</script>

Save the changes to your file.

In order to keep the component and the configuration separate, you will next be creating a new file for the chart data.

Step 3 — Creating the Chart Data

Creating a chart with Chart.js resembles the following:

const ctx = document.getElementById('example');
const exampleChart = new Chart(ctx, {
  type: '',
  data: [],
  options: {},
});

A <canvas> element is passed in along with a type, data, and options.

You will be creating a new file that defines these values. Open your code editor and under src directory, create a new planet-data.js file. Keep in mind, you will want to give it a unique and descriptive name based on the data. You can have several data objects in this file for different charts.

Add the following lines of code to planet-data.js:

src/planet-data.js
export const planetChartData = {
  type: "line",
  data: {
    labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
    datasets: [
      {
        label: "Number of Moons",
        data: [0, 0, 1, 2, 79, 82, 27, 14],
        backgroundColor: "rgba(54,73,93,.5)",
        borderColor: "#36495d",
        borderWidth: 3
      },
      {
        label: "Planetary Mass (relative to the Sun x 10^-6)",
        data: [0.166, 2.081, 3.003, 0.323, 954.792, 285.886, 43.662, 51.514],
        backgroundColor: "rgba(71, 183,132,.5)",
        borderColor: "#47b784",
        borderWidth: 3
      }
    ]
  },
  options: {
    responsive: true,
    lineTension: 1,
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
            padding: 25
          }
        }
      ]
    }
  }
};

export default planetChartData;

The type will be set to line. The data will consist of of two datasets, backgroundColor, borderColor, and borderWidth. The options will consist of responsive, lineTension, and scales.

Note: You can reference the Chart.js documentation for more information about line charts, as well as others like bar, polarArea, radar, pie, and doughnut.

By exporting planetChartData, you are allowing that const to be imported into another JavaScript file. More importantly, you are separating the data from the component. This best practice allows you to apply changes to only the relevant file and offers greater maintenance over time.

Revisit the PlanetChart component and add planetChartData:

src/components/PlanetChart.vue
<script>
import Chart from 'chart.js'
import planetChartData from '../planet-data.js'

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

Next, store the chart data in the data() function.

src/components/PlanetChart.vue
<script>
import Chart from 'chart.js'
import planetChartData from '../planet-data.js'

export default {
  name: 'PlanetChart',
  data() {
    return {
      planetChartData: planetChartData
    }
  }
}
</script>

Note: You can also use ES6 shorthand. Since the data property and value have the same name, you can just use planetChartData instead of planetChartData: planetChartData.

At this point, Chart.js should be installed and the chart’s data should be imported into the PlanetChart component.

You should already have a <canvas> element created in the component’s template. At this point, it’s time to initialize the chart and write to the <canvas>.

Revisit the PlanetChart component and add the create the chart in the mounted() lifecycle method:

src/components/PlanetChart.vue
<script>
import Chart from 'chart.js'
import planetChartData from '../planet-data.js'

export default {
  name: 'PlanetChart',
  data() {
    return {
      planetChartData: planetChartData
    }
  },
  mounted() {
    const ctx = document.getElementById('planet-chart');
    new Chart(ctx, this.planetChartData);
  }
}
</script>

Save the changes to your file.

Now, you can run your application with your terminal:

  • npm run serve

Open the application in your web browser:

Screenshot of line charts of the number of moons and planetary mass.

There will be two line charts. One chart displays the number of moons for each planet. THe other chart displays the mass of each planet. The backgroundColor, borderColor, and borderWidth values have affected the appearance of the charts. Interacting with the points on the line will display the labels.

Step 4 — Displaying Mixed Charts

Chart.js also supports mixed charts. In this section, you will change the configuration of the charts from line charts to a mix of a line chart for the moon dataset and a bar chart for the mass dataset.

Revisit planet-data.js with your code editor. Modify the type property of your chart’s data and change it to bar.

src/planet-data.js
export const planetChartData = {
  type: "bar",
  data: { ... },
  options: { ... }
};

export default planetChartData;

At this point, both charts will be bar graphs.

However, you want to display a mix of bar and line graphs. To change this, in each dataset object, add a type property under the label property. For the first dataset object, give it a type property with a value of line and for the second, give it a type property with a value of bar:

src/planet-data.js
export const planetChartData = {
  type: "bar",
  data: {
    labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
    datasets: [
      {
        label: "Number of Moons",
        type: "line',
        data: [0, 0, 1, 2, 79, 82, 27, 14],
        backgroundColor: "rgba(54,73,93,.5)",
        borderColor: "#36495d",
        borderWidth: 3
      },
      {
        label: "Planetary Mass (relative to the Sun x 10^-6)",
        type: "bar",
        data: [0.166, 2.081, 3.003, 0.323, 954.792, 285.886, 43.662, 51.514],
        backgroundColor: "rgba(71, 183,132,.5)",
        borderColor: "#47b784",
        borderWidth: 3
      }
    ]
  },
  options: { ... }
};

export default planetChartData;

Save the changes to your file.

Now, you can run your application with your terminal:

  • npm run serve

Open the application in your web browser:

Screenshot of line chart of moons and bar chart of planetary mass.

The number of moons for each planet displays as a line chart. The mass of each planet displays as a bar chart.

Conclusion

In this article, you used Chart.js in a sample Vue project to display information about planets in the solar system.

Chart.js can be used for other data visualizations. Explore the samples for inspiration in how it can be incorporated into your projects.

Creative Commons License