简体   繁体   中英

How can I show percentages when hovering over my chart?

SITUATION:

I am looking to add a percentage next to the number tooltip you get when hovering over your chart. How can I achieve that? For example, I would like to add a % sign next to 83.33 .

在此处输入图片说明


ERROR:

ERROR TypeError: Cannot read property '0' of undefined
at i.label (eval at <anonymous> (http://localhost:3000/js/app/bundle.js:1564:1), <anonymous>:37:63)

CODE:

// Pie
public pieChartLabels:string[] = [];
public pieChartData:number[] = [];
public pieChartType:string = 'pie';
public pieChartOptions:any = {};

ngOnInit() {
    var result1 = parseFloat(((this.poll.counter1/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
    var result2 = parseFloat(((this.poll.counter2/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
    this.pieChartData = [result1, result2];
    this.pieChartLabels = [this.poll.choice1, this.poll.choice2];
    this.pieChartType = 'pie';
    this.pieChartOptions  = {
                            tooltips: {
                                callbacks: {
                                    label: function (tooltipItems, data) {
                                            return data.datasets[tooltipItems.datasetIndex].label + ': ' +
                                                tooltipItems.pieChartLabels[tooltipItems.datasetIndex].replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                                           }
                                    }
                                }

                            }

    // events
public chartClicked(e:any):void {

}

public chartHovered(e:any):void {

}

You can use tooltips callback in chart.js to change the tooltip suffix. Here is an example on how to add %. I hacked this together by doing some searches and finding other examples.

https://jsfiddle.net/nt50dzb7/

  options: {
    tooltips: {
      enabled: true,
      mode: 'single',
      callbacks: {
        label: function(tooltipItem, data) {
          var allData = data.datasets[tooltipItem.datasetIndex].data;
          var tooltipLabel = data.labels[tooltipItem.index];
          var tooltipData = allData[tooltipItem.index];
          return tooltipLabel + ": " + tooltipData + "%";
        }
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM