5

I am trying to configure and use datalabels plugin for chartjs but no success. I am using npm as project management tool so added plugin using '

npm install --save chartjs-plugin-datalabels

Imported it in my component

import ChartJSPluginDatalabels from "chartjs-plugin-datalabels";

Added it in components dependency

components: {
    ChartJSPluginDatalabels,
    ... }

Added it in options

  data: () => ({
    options: {
      responsive: true,
      maintainAspectRatio: false,
      tooltips:{
          enabled : true
      },
      plugins: {
        datalabels: {
            formatter: (value, ctx) => {
                
                let sum = 0;
                let dataArr = ctx.chart.data.datasets[0].data;
                dataArr.map(data => {
                    sum += data;
                });
                let percentage = (value*100 / sum).toFixed(2)+"%";
                return percentage;
            },
            color: '#fff',
        }
     }   
    }

Binded options with chartjs component

 <service-demand :width="300" :height="300"  :chartData="topServices" :options="options">/service-demand>

But its not working.

Any suggestion? I am using vuejs 2 and below is my package.json dependencies snippet

 "dependencies": {
    "axios": "^0.21.1",
    "chart.js": "^2.9.4",
    "core-js": "^2.6.12",
    "echarts": "^5.0.0",
    "express": "^4.17.1",
    "moment": "^2.29.1",
    "serve-static": "^1.14.1",
    "vue": "^2.6.12",
    "vue-chartjs": "^3.5.1",
    "vue-echarts": "^5.0.0-beta.0",
    "vue-i18n": "^8.22.2",
    "vue-peity": "^0.5.0",
    "vue-router": "^3.4.9",
    "vue2-google-maps": "^0.10.7",
    "vuetify": "^2.3.21",
    "vuex": "^3.6.0",
    "chartjs-plugin-datalabels": "^1.0.0"
  },

1 Answer 1

7

On vuejs 2, don't forget to use register

import ChartJSPluginDatalabels from 'chartjs-plugin-datalabels'
  
ChartJS.register(ChartJSPluginDatalabels, ...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.