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.
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.
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.
This chart will consist of two datasets:
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.
<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
:
<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.
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
:
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
:
<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.
<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:
<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:
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
.
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
.
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
:
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:
The number of moons for each planet displays as a line chart. The mass of each planet displays as a bar chart.
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Great walkthrough. Helped me a lot. Just 2 remarks:
First off, thank you for a well written guide!
I’ve been struggling with a variety of errors for days trying to use either v-charts and vue-echarts with echarts, but today I decided to just try Chart.js. This guide was the clearest and to-the-point of many, but I’m currently stuck after following the steps…
npm packages: ├── @vue/cli@4.5.12 ├── @vue/composition-api@1.0.0-rc.6 ├── chart.js@3.0.2 ├── echarts@5.0.2 ├── vue-chartjs@3.5.1 ├── vue-echarts@6.0.0-rc.4 └── vue@2.6.12
Copy pasting your code, I get the error:
"Error in mounted hook: “TypeError: chart_js__WEBPACK_IMPORTED_MODULE_0__.default is not a constructor”
found in
—> <PlanetChart> at src/components/PlanetChart.vue <App> at src/App.vue <Root>"
Do you have any idea what could’ve gone wrong? :S
Awesome! Thanks a lot. This works with vue3! Tried vue-chartjs package and it does not support vue3. So this saved me.