Search code examples
vue.jsvuejs2vue-chartjs

Vuejs How can I add colors to vue-chartjs Doughnut?


I'm trying to implement vue-chartjs Doughnut but I cant get the colors right.

enter image description here

This is where I used the component Doughnut

my App.vue

<template>
  <div id="app">
    <label for="Doughnut">Doughnut</label>
    <div id="ChartDoughnut">
      <ChartDoughnut :chartData="chartDataDoughnut" />
    </div>
  </div>
</template>

<script>
import ChartDoughnut from "./components/ChartDoughnut.vue";
export default {
  name: "App",
  components: {
    ChartDoughnut
  },
  data() {
    return {
      chartDataDoughnut: {
        datasets: [
          {
            data: [10, 20, 30]
          }
        ],

        // These labels appear in the legend and in the tooltips when hovering different arcs
        labels: ["Red", "Yellow", "Blue"]
      }
      // optionsDoughnut: {}
    };
  }
};
</script>

This is the component for Doughnut

chartDoughnut.vue

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

export default {
  extends: Doughnut,
  props: {
    chartData: {
      type: Object,
      default: null
    },
    options: {
      type: Object,
      default: null
    }
  },
  mounted() {
    this.renderChart(this.chartData);
  }
};
</script>

I have added color on the labels but it's not working.


Solution

  • Try adding the backgroundColor property with a color array to your datasets property.

    backgroundColor: ['red', 'yellow', 'blue']
    

    // The important part: the Chart component
    Vue.component('chart', {
       extends: VueChartJs.Doughnut,
      props: {
        chartData: {
          type: Object,
          default: null
        },
        options: {
          type: Object,
          default: null
        }
      },
      mounted() {
        this.renderChart(this.chartData);
      }
    })
    
    //App setup
    new Vue({
    	el:'#vue',
      data(){
      	return {
            chartDataDoughnut: {
              datasets: [
                {
                  data: [10, 20, 30],
                  backgroundColor: ['red', 'yellow', 'blue']
                }
              ],
              labels: ["Red", "Yellow", "Blue"]
            }
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
    <script src="https://unpkg.com/vue-chartjs/dist/vue-chartjs.min.js"></script>
    
    <div id="vue">
      <chart :chart-data="chartDataDoughnut"></chart>
    </div>