Categories
Vue Answers

How to Dynamically Change of Chart Type with Chart.js?

Spread the love

To dynamically change the chart type using Chart.js, you need to destroy the existing chart instance and create a new one with the updated chart type.

To do this we follow:

1. Set Up Chart.js

First, ensure you have Chart.js installed and set up in your project.

2. Create a Vue Component for the Chart

Create a Vue component where you initialize and render the Chart.js chart.

3. Add a Method to Change Chart Type Dynamically

Implement a method in the component to change the chart type dynamically.

Here’s a basic example of how to achieve this:

<template>
  <div>
    <canvas id="myChart" width="400" height="400"></canvas>
    <button @click="changeChartType">Change Chart Type</button>
  </div>
</template>

<script>
import Chart from 'chart.js';

export default {
  data() {
    return {
      chart: null,
      chartType: 'bar', // Initial chart type
    };
  },
  mounted() {
    this.renderChart();
  },
  methods: {
    renderChart() {
      const ctx = document.getElementById('myChart').getContext('2d');
      this.chart = new Chart(ctx, {
        type: this.chartType,
        data: {
          // Your chart data
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
          datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            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)'
            ],
            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)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          // Your chart options
        }
      });
    },
    changeChartType() {
      // Destroy the existing chart
      this.chart.destroy();
      
      // Change the chart type
      this.chartType = (this.chartType === 'bar') ? 'line' : 'bar';
      
      // Render the new chart
      this.renderChart();
    }
  }
};
</script>

In this example, the changeChartType method toggles between ‘bar’ and ‘line’ chart types.

It destroys the existing chart instance, updates the chartType variable, and then re-renders the chart with the new type. You can modify this method to accommodate other chart types and customize it further based on your requirements.

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 *