我是Ionic的初学者2.我使用Chart.js Library在混合移动应用程序中显示饼图。
我已经成功地在饼图中显示数据,但显示数字,我想显示百分比而不是数字。
这是我的代码
this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {
type: 'doughnut',
data: {
labels: data1, //data1 contains [100 ,50 ,200 ,500 ,60]
datasets: [{
label: '# of Votes',
data: data2, //data2 contains [Gerberea,Lili,Rose,Sunflower,Lotus]
backgroundColor: [
'rgba(0, 99, 132, 0.2)',
'rgba(25, 162, 235, 0.2)',
'rgba(50, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(100, 102, 255, 0.2)',
'rgba(125, 159, 64, 0.2)'
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56",
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
}
});
答案 0 :(得分:0)
在tooltips
中使用options
,您可以计算其中的百分比并显示为label
。
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue;
});
var currentValue = dataset.data[tooltipItem.index];
var precentage = ((currentValue/total) * 100).toFixed(2);
return precentage + "%";
}
}
}
}
演示样本
var config = {
type: 'doughnut',
data: {
labels: ['Gerberea', 'Lili', 'Rose', 'Sunflower', 'Lotus'],
datasets: [{
label: '# of Votes',
data: [100, 50, 200, 500, 60],
backgroundColor: [
'rgba(0, 99, 132, 0.2)',
'rgba(25, 162, 235, 0.2)',
'rgba(50, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(100, 102, 255, 0.2)',
'rgba(125, 159, 64, 0.2)'
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56",
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue;
});
var currentValue = dataset.data[tooltipItem.index];
var precentage = ((currentValue / total) * 100).toFixed(2);
return precentage + "%";
}
}
}
}
};
var ctx = document.getElementById("chart-area").getContext("2d");
window.myDoughnut = new Chart(ctx, config); {
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.bundle.js"></script>
<canvas id="chart-area" />
&#13;