Create a Chart using chartJs in VueJs

  125 views   2 months ago VueJs

This tutorial expounds about how to engender awe-inspiring charts that will avail us to understand the data or information in meaning full ways. I will show you how to engender pulchritudinous charts in Vue.js 2+ app utilizing Chart.js and vue-chartjs plugin.
Data visualization is a consequential aspect nowadays, and Charts are the best implements to represent the information for everybody. Charts process our encephalons to understand the data more facilely and expeditiously than the textual information. The most critical information can be facilely scanned with the avail of Charts, which is not possible in a textual form of data.

Vue.js is a lenient JavaScript framework to engender utilizable utilizer-interfaces. We will take the avail of Chart.js and vue-chartjs to manifest the chart examples.

So, Let’s get commenced.

Install Vue Project with Vue CLI

First, we have to install the Vue CLI using given below command:

npm install -g @vue/cli

Next, we can install the Vue project:

vue create vue-chart-js-app

Vue CLI asks following question:

# ? Please pick a preset: Manually select features
# ? Check the features needed for your project: Babel, Router, CSS Pre-processors, Linter
# ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
# ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass)
# ? Pick a linter / formatter config: Basic
# ? Pick additional lint features: Lint on save
# ? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
# ? Save this as a preset for future projects? (y/N) No

Get inside the project:

cd vue-chart-js-app

Let’s start the project and check in the browser:

npm run serve

Install Chart.js and vue-chartjs Plugins

Run the command to install vue-chartjs and Chart.js plugins.

# npm
npm install vue-chartjs chart.js --save

# yarn
yarn add vue-chartjs chart.js

Chart.js is a powerful, straightforward, yet flexible open-source JavaScript library for software developers. It helps in creating various stunning charts using HTML5 canvas. It is a well-known library, and you can figure out the popularity of this library by seeing more than 48.1k+ stars on GitHub.

You can draw the following charts with Chart.js:

  • Line
  • Bar
  • Doughnut
  • Pie
  • Radar
  • Polar Area
  • Bubble
  • Scatter

The vue-chartjs provides a wrapper for Chart.js in Vue. It allows creating reusable chart components to display useful information that can be easily understood graphically. This plugin is highly compatible with Vue.js 2.x +.

Creating & Setting Up Charts Components

In this step, we will create components and views for the charts examples.

Create the given below files inside the src/views folder:

  • Line.vue => (Home.vue)
  • Bar.vue
  • Doughnut.vue
  • Pie.vue
  • Radar.vue
  • PolarArea.vue
  • Bubble.vue
  • Scatter.vue

Next, create the given below src/components folder:

  • LineChart.vue
  • BarChart.vue
  • DoughnutChart.vue
  • PieChart.vue
  • RadarChart.vue
  • PolarAreaChart.vue
  • BubbleChart.vue
  • ScatterChart.vue

Create & Set up Routes in Vue

Now, we need to create and configure the routes in our Vue app. These routes will allow us to display the charts from the component we generated above.

Open router/index.js file and replace the existing code with the following code.

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

  const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/bar',
    name: 'Bar',
    component: () => import('../views/Bar.vue')
  },
  {
    path: '/doughnut',
    name: 'Doughnut',
    component: () => import('../views/Doughnut.vue')
  },
  {
    path: '/pie',
    name: 'Pie',
    component: () => import('../views/Pie.vue')
  },
  {
    path: '/radar',
    name: 'Radar',
    component: () => import('../views/Radar.vue')
  },
  {
    path: '/polar-area',
    name: 'PolarArea',
    component: () => import('../views/PolarArea.vue')
  },
  {
    path: '/bubble',
    name: 'Bubble',
    component: () => import('../views/Bubble.vue')
  },
  {
    path: '/scatter',
    name: 'Scatter',
    component: () => import('../views/Scatter.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

Open src/App.vue and replace the current code with the given blow code.

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Line</router-link> |
      <router-link to="/bar">Bar</router-link> |
      <router-link to="/doughnut">Doughnut</router-link> |
      <router-link to="/pie">Pie</router-link> |
      <router-link to="/radar">Radar</router-link> |
      <router-link to="/polar-area">Polar Area</router-link> |
      <router-link to="/bubble">Bubble</router-link> |
      <router-link to="/scatter">Scatter</router-link>
    </div>

    <div class="container">
      <div class="row">
        <div class="col-12">
          <router-view />
        </div>
      </div>
    </div>

  </div>
</template>

<style lang="scss">
  #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 30px 60px;

    a {
      font-weight: bold;
      color: #2c3e50;

      &.router-link-exact-active {
        color: #42b983;
      }
    }
  }
</style>

We enabled the navigation in Vue by defining the router-link inside the src/App.vue file.

The <router-view /> directive will display the associated view for the particular Chart component.

Vue Line Chart Example

Now, we will create a line chart. Go to components/LineChart.vue and place the following code.

<script>
  import { Line } from 'vue-chartjs'

  export default {
    extends: Line,
    data () {
      return {
        chartData: {
          labels: ["Babol",	"Cabanatuan",	"Daegu",	"Jerusalem",	"Fairfield",	"New York",	"Gangtok", "Buenos Aires", "Hafar Al-Batin", "Idlib"],
          datasets: [
            {
              label: 'Line Chart',
              data: [600,	1150,	342,	6050,	2522,	3241,	1259,	157,	1545, 9841],
              fill: false,
              borderColor: '#2554FF',
              backgroundColor: '#2554FF',
              borderWidth: 1
            }
          ]
        },
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      this.renderChart(this.chartData, this.options)
    }
  }
</script>

Next, open the views/Home.vue. Here, we will display the Line chart, so add the line-chart tag and import the LineChart component inside the view.

<template>
  <div>
    <h3>Line Chart Example in Vue</h3>
    <line-chart></line-chart>
  </div>
</template>

<script>
import LineChart from '@/components/LineChart'

export default {
  components: {
    LineChart
  }
}
</script>

Bar Chart Example in Vue

To create a Bar chart, open components/BarChart.vue file and place the following code.

<script>
  import { Bar } from 'vue-chartjs'

  export default {
    extends: Bar,
    data() {
      return {
        chartData: {
          labels: ["2015-01", "2015-02", "2015-03", "2015-04", "2015-05", "2015-06", "2015-07", "2015-08", "2015-09",
            "2015-10", "2015-11", "2015-12"
          ],
          datasets: [{
            label: 'Bar Chart',
            borderWidth: 1,
            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)',
              '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)',
              '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)'
            ],
            pointBorderColor: '#2554FF',
            data: [12, 19, 3, 5, 2, 3, 20, 3, 5, 6, 2, 1]
          }]
        },
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [{
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted() {
      this.renderChart(this.chartData, this.options)
    }
  }
</script>

Next, open the views/Bar.vue file. Here, we have to show the Bar chart, so add the bar-chart tag inside the template directive and import the BarChart component in the view.

<template>
  <div>
    <h3>Bar Chart Example in Vue</h3>
    <bar-chart></bar-chart>
  </div>
</template>

<script>
import BarChart from '@/components/BarChart'

export default {
  components: {
    BarChart
  }
}
</script>

Vue Doughnut Chart Example

To create a Doughnut chart, open components/DoughnutChart.vue file and add the following code.

<script>
  import { Doughnut } from 'vue-chartjs'

  export default {
    extends: Doughnut,
    data () {
      return {
        chartData: {
          labels: ["Babol",	"Cabanatuan",	"Daegu",	"Jerusalem"],
          datasets: [{
              borderWidth: 1,
              borderColor: [
              'rgba(255,99,132,1)',
              'rgba(54, 162, 235, 1)',
              'rgba(255, 206, 86, 1)',
              'rgba(75, 192, 192, 1)'                
              ],
              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)',                
              ],
              data: [1000,	500,	1500,	1000]
            }]
        },
        options: {
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      this.renderChart(this.chartData, this.options)
    }
  }
</script>

Next, open the views/Doughnut.vue file. Here, we have to show the Doughnut chart, so add the doughnut-chart tag inside the template directive and import the DoughnutChart component in the view.

<template>
  <div>
    <h3>Doughnut Chart Example in Vue</h3>
    <doughnut-chart></doughnut-chart>
  </div>
</template>

<script>
import DoughnutChart from '@/components/DoughnutChart'

export default {
  components: {
    DoughnutChart
  }
}
</script>

Pie Chart Example in Vue

To create a Pie chart, open components/PieChart.vue file and add the following code.

<script>
  import { Pie } from 'vue-chartjs'

  export default {
    extends: Pie,
    data () {
      return {
        chartData: {
          labels: ["Italy", "India", "Japan", "USA",],
          datasets: [{
              borderWidth: 1,
              borderColor: [
              'rgba(255,99,132,1)',
              'rgba(54, 162, 235, 1)',
              'rgba(255, 206, 86, 1)',
              'rgba(75, 192, 192, 1)'            
              ],
              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)',                
              ],
              data: [1000,	500,	1500,	1000]
            }]
        },
        options: {
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      this.renderChart(this.chartData, this.options)
    }
  }
</script>

Next, open the views/Pie.vue file. Here, we have to show the Pie chart, so add the pie-chart tag inside the template directive and import the PieChart component in the view.

<template>
  <div>
    <h3>Pie Chart Example in Vue</h3>
    <pie-chart></pie-chart>
  </div>
</template>

<script>
import PieChart from '@/components/PieChart'

export default {
  components: {
    PieChart
  }
}
</script>

Radar Chart Example

To create a Radar chart, open components/RadarChart.vue file and add the following code.

<script>
  import { Radar } from 'vue-chartjs'

  export default {
    extends: Radar,
    data () {
      return {
        chartData: {
          labels: [
             "Babol",	
             "Cabanatuan",	
             "Daegu",	
             "Jerusalem",	
             "Fairfield",	
             "New York",
             "Gangtok", 
             "Buenos Aires", 
             "Hafar Al-Batin", 
             "Idlib"
          ],
          datasets: [
            {
              label: 'Radar Chart',
              borderWidth: 1,
              backgroundColor: 'rgba(54, 162, 235, 0.2)',
             
              data: [
                32127289, 
                24724027, 
                25820412, 
                23685667, 
                25644258, 
                22433220, 
                22966210, 
                22743184, 
                21880515, 
                21543111
              ]
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      this.renderChart(this.chartData, this.options)
    }
  }
</script>

Next, open the views/Radar.vue file. Here, we have to show the Radar chart, so add the radar-chart tag inside the template directive and import the RadarChart component in the view.

<template>
  <div>
    <h3>Radar Chart Example in Vue</h3>
    <radar-chart></radar-chart>
  </div>
</template>

<script>
import RadarChart from '@/components/RadarChart'

export default {
  components: {
    RadarChart
  }
}
</script>

Polar Area Chart Example

To create a Polar Area chart, open components/PolarAreaChart.vue file and add the following code.

<script>
  import { PolarArea } from 'vue-chartjs'

  export default {
    extends: PolarArea,
    data () {
      return {
        chartData: {
          labels: ['Pink', 'Blue', 'Yellow', 'Green', 'Purple'],
          datasets: [
            {
              label: 'Polar Area Chart',
              borderWidth: 1,
              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)',                
              ],
              data: [8, 14, 12, 7, 20]
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      this.renderChart(this.chartData, this.options)
    }
  }
</script>

Next, open the views/PolarArea.vue file. Here, we have to show the PolarArea chart, so add the polar-area-chart tag inside the template directive and import the PolarAreaChart component in the view.

<template>
  <div>
    <h3>Polar Area Chart Example in Vue</h3>
    <polar-area-chart></polar-area-chart>
  </div>
</template>

<script>
import PolarAreaChart from '@/components/PolarAreaChart'

export default {
  components: {
    PolarAreaChart
  }
}
</script>

Bubble Chart Example

In this step we will create Bubble Area chart, so open the components/BubbleChart.vue file and add the given below code.

<script>
  import { Bubble } from 'vue-chartjs'

  export default {
    extends: Bubble,
    data() {
      return {
        chartData: {
          datasets: [{
            label: 'Population Data',
            borderWidth: 1,
            borderColor: '#2554FF',
            backgroundColor: '#2554FF',
            data: [{
                x: 6,
                y: 3,
                r: 15
              }, {
                x: 3,
                y: 12,
                r: 4
              },
              {
                x: 5,
                y: 15,
                r: 10
              },
              {
                x: 3,
                y: 12,
                r: 8
              },
              {
                x: 4,
                y: 5,
                r: 20
              },
              {
                x: 2,
                y: 6,
                r: 3
              },
              {
                x: 4,
                y: 9,
                r: 11
              },
              {
                x: 5,
                y: 10,
                r: 6
              }
            ]
          }]
        },
        options: {
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted() {
      this.renderChart(this.chartData, this.options)
    }
  }
</script>

Then, go to views/Bubble.vue file. Here, we need to display the Bubble chart, so add the bubble-chart tag inside the vue’s template directive and import the BubbleChart component in the view.

<template>
  <div>
    <h3>Bubble Chart Example in Vue</h3>
    <bubble-chart></bubble-chart>
  </div>
</template>

<script>
import BubbleChart from '@/components/BubbleChart'

export default {
  components: {
    BubbleChart
  }
}
</script>

Scatter Chart Example

In this step we will create Bubble Area chart, so open the components/ScatterChart.vue file and add the given below code.

<script>
  import { Scatter } from 'vue-chartjs'

  export default {
    extends: Scatter,
    data() {
      return {
        chartData: {
          datasets: [{
            label: 'Population Data',
            borderWidth: 1,
            borderColor: '#2554FF',
            backgroundColor: '#2554FF',
            data: [{
                x: 6,
                y: 3,
                r: 15
              }, {
                x: 3,
                y: 12,
                r: 4
              },
              {
                x: 5,
                y: 15,
                r: 10
              },
              {
                x: 3,
                y: 12,
                r: 8
              },
              {
                x: 4,
                y: 5,
                r: 20
              },
              {
                x: 2,
                y: 6,
                r: 3
              },
              {
                x: 4,
                y: 9,
                r: 11
              },
              {
                x: 5,
                y: 10,
                r: 6
              }
            ]
          }]
        },
        options: {
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted() {
      this.renderChart(this.chartData, this.options)
    }
  }
</script>

Then, go to views/Scatter.vue file. Here, we need to display the Scatter chart, so add the scatter-chart tag inside the vue’s template directive and import the ScatterChart component in the view.

<template>
  <div>
    <h3>Scatter Chart Example in Vue</h3>
    <scatter-chart></scatter-chart>
  </div>
</template>

<script>
import ScatterChart from '@/components/ScatterChart'

export default {
  components: {
    ScatterChart
  }
}
</script>

i hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles