Categories
JavaScript Vue

Creating Bar Chart with vue-chartjs

Spread the love

vue-chartjs is an easy to use library for adding charts to our Vue app.

We can install it by running:

npm i vue-chartjs chart.js

Then we can use it as follows:

BarChart.vue

<script>
import { Bar } from "vue-chartjs";

export default {
  extends: Bar,
  props: ["data", "options"],
  mounted() {
    this.renderChart(this.data, this.options);
  }
};
</script>

App.vue

<template>
  <div id="app">
    <BarChart :data="data" :options="options"/>
  </div>
</template>

<script>
import BarChart from "./components/BarChart";

export default {
  name: "App",
  components: {
    BarChart
  },
  data() {
    return {
      data: {
        labels: ["January", "February"],
        datasets: [
          {
            label: "Data One",
            backgroundColor: "#f87979",
            data: [40, 30]
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          yAxes: [
            {
              display: true,
              ticks: {
                suggestedMin: 0,
                beginAtZero: true
              }
            }
          ]
        }
      }
    };
  }
};
</script>

The code above just passes the data from App.vue to the BarChart.vue, which renders the bar graph according to the props that we passed in.

We specified the axes options by writing:

scales: {
  yAxes: [
    {
       display: true,
       ticks: {
         suggestedMin: 0,
         beginAtZero: true
       }
    }
  }
}

With the beginAtZero, the scale of the axis will begin at 0.

We specified that the y-axis begins with 0.

The datasets property has all the data for the bars and the color for the bars.

The label is displayed at the legend.

In the end, we get:

https://thewebdev.info/wp-content/uploads/2020/04/chart.png

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *