Chartjs - Insert % at end of value in tooltip

Asked

Viewed 1,095 times

1

I’m doing an angular Chart.js and need to place the percent ( % ) at the end of each tooltip where it shows the value on the chart.

Follow code from my chart:

Html:

<canvas class="chart chart-doughnut" chart-data="vm.data" chart-labels="vm.labels" chart-colors="vm.colors" chart-options="vm.options" ng-init="vm.chart()"></canvas>

JS:

vm.chart = () => {
        vm.labels = ["D1", "VC1", "Internacional", "À cobrar", "0300", "Gratuita", "Locais"];
        vm.colors = [ '#f36e20', '#8aca7b', '#0bc4df', '#272343', '#389223', '#f1a80a', '#1e75eb'];
        vm.data = [10, 10, 20, 10, 10, 10, 30];
        vm.options = {
        }
    }

Does anyone know if it is in the options that I enter this option?

vm.data only accepts integers, it may have some method of inserting decimal values and with them %.

  • What text appears in tooltip?

  • Value of vm.data appears.

1 answer

1


Done.

Based on Chartjs documentation:

The tool label configuration is nested below the tool tip configuration using return key from call. The tooltip has the following call returns to provide text. For all functions, "this" will be the hint object of tool created from the Chart.Tooltip constructor.

All functions are called with the same arguments: an item of tooltip and the data object passed to the chart. All functions must return a string or a string array. Arrays of strings are treated as multiple lines of text.

 vm.options = {
    tooltips: {
      callbacks: {
        label: (tooltipItem, chart) => {
          const realValue = chart.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]
          const customValue = realValue.toFixed(2).replace(".", ",") + '%';
          const label = chart.labels[tooltipItem.index] + ':';
          return label + customValue;
        }
      }
    }
  }

Link in jsfiddle running.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.