我使用Chart.js作为甜甜圈图表。在徘徊在甜甜圈部分时,我试图展示“40%的人”。但它会在“数据集”中显示数据。对象显示' People 40%:40'。如果你悬停在甜甜圈的海军部分,你会看到数据显示。我已尝试过对数据阵列进行javascript拆分和拼接,但无法将其删除:40。我的问题是如何展示:' People 40%'而不是每个标签的人40%:40'等等?
https://codepen.io/zepzia/pen/WdrWww
<div class="wrapper">
<canvas id="commitments-area" width="200" height="200"></canvas>
</div>
.wrapper {
height: 200px;
width: 200px;
margin: 0 auto;
}
var oilCanvas = document.getElementById("commitments-area");
Chart.defaults.global.defaultFontSize = 12;
Chart.defaults.global.legend.display = false;
Chart.defaults.global.tooltips;
var oilData = {
labels: [
"People (40%)",
"Aliens (32%)",
"Dogs (13%)",
"Whales (15%)"
],
datasets: [
{
data: [40, 32, 13, 15],
backgroundColor: [
"#13284a",
"#4b9cd3",
"#3b7ca7",
"#99cdec",
"#84d1ff"
]
}]
};
var chartOptions = {
legend: {
position: 'bottom'
},
animation: {
animateRotate: true,
animateScale: true
},
};
var pieChart = new Chart(oilCanvas, {
type: 'doughnut',
data: oilData,
options: chartOptions
});
答案 0 :(得分:2)
这是答案,我在这里发布了来自codepen的js,看到更新的“选项”,片段底部的“return tootipLabel”部分,以获得您正在寻找的X%结果。
感谢http://blog.cryst.co.uk/2016/06/03/adding-percentages-chart-js-pie-chart-tooltips/指出我正确的方向:
var oilCanvas = document.getElementById("commitments-area");
Chart.defaults.global.defaultFontSize = 12;
Chart.defaults.global.legend.display = false;
Chart.defaults.global.tooltips;
var oilData = {
labels: [
"People",
"Aliens",
"Dogs",
"Whales"
],
datasets: [
{
data: [40, 32, 13, 15],
backgroundColor: [
"#13284a",
"#4b9cd3",
"#3b7ca7",
"#99cdec",
"#84d1ff"
]
}]
};
var chartOptions = {
legend: {
position: 'bottom'
},
animation: {
animateRotate: true,
animateScale: true
},
};
var pieChart = new Chart(oilCanvas, {
type: 'doughnut',
data: oilData,
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var allData = data.datasets[tooltipItem.datasetIndex].data;
var tooltipLabel = data.labels[tooltipItem.index];
var tooltipData = allData[tooltipItem.index];
var total = 0;
for (var i in allData) {
total += allData[i];
}
var tooltipPercentage = Math.round((tooltipData / total) * 100);
return tooltipLabel + ': ' + ' ' + tooltipPercentage + '%';
}
}
}
}
});
.wrapper {
height: 200px;
width: 200px;
margin: 0 auto;
}
<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.5.0/Chart.min.js"></script>
<div class="wrapper">
<canvas id="commitments-area" width="200" height="200"></canvas>
</div>