我正在使用react-chartjs-2来自定义三个甜甜圈饼图。这个库有很多功能,但我在这里遇到了问题。我不知道如何处理零值。当我的所有值都为零时,不会绘制饼图,这是正确的。任何关于如何处理零值的想法?这是我绘制圆环饼图的代码:
const renderPortfolioSectorPie = (sectors, intl) => {
if (sectors.length > 0) {
const sectorsName = sectors
.map(sector => sector.name);
const sectorsValue = sectors
.map(sector => sector.subtotal);
const sectorsPercentage = sectors
.map(sector => sector.percentage);
const customeSectorsPercentage = sectorsPercentage.map(h =>
`(${h})`
);
let sectorsCounter = 0;
for (let i = 0; i < sectorsName.length; i += 1) {
if (sectorsName[i] !== sectorsName[i + 1]) {
sectorsCounter += 1;
}
}
const sectorsData = {
datasets: [{
data: sectorsValue,
backgroundColor: [
'#129CFF',
'#0c6db3',
'#4682B4',
'#00FFFF',
'#0099FF',
'#3E3BF5',
'#3366CC',
'#3399FF',
'#6600FF',
'#3366CC',
'#0099CC',
'#336699',
'#3333FF',
'#2178BA',
'#1F7AB8',
'#1C7DB5'
],
hoverBackgroundColor: [
'#129cff',
'#0c6db3',
'#4682B4',
'#00FFFF',
'#0099FF',
'#3E3BF5',
'#3366CC',
'#3399FF',
'#3366CC',
'#0099CC',
'#336699',
'#3333FF',
'#2178BA',
'#1F7AB8',
'#1C7DB5'
],
titles: sectorsName,
labels: sectorsValue,
afterLabels: customeSectorsPercentage,
}]
};
return (
<Doughnut
data={sectorsData}
width={250}
height={250}
redraw
options={{
legend: {
display: false
},
maintainAspectRatio: true,
responsive: true,
cutoutPercentage: 80,
animation: {
animateRotate: false,
animateScale: false
},
elements: {
center: {
textNumber: `${sectorsCounter}`,
text: intl.formatMessage({ id: 'pie.sectors' }),
fontColor: '#4a4a4a',
fontFamily: "'EurobankSans'",
fontStyle: 'normal',
minFontSize: 25,
maxFontSize: 25,
}
},
/*eslint-disable */
tooltips: {
custom: (tooltip) => {
tooltip.titleFontFamily = 'Helvetica';
tooltip.titleFontColor = 'rgb(0,255,255)';
},
/* eslint-enable */
callbacks: {
title: (tooltipItem, data) => {
const titles = data.datasets[tooltipItem[0]
.datasetIndex].titles[tooltipItem[0].index];
return (
titles
);
},
label: (tooltipItem, data) => {
const labels = data.datasets[tooltipItem.datasetIndex]
.labels[tooltipItem.index];
return (
labels
);
},
afterLabel: (tooltipItem, data) => {
const afterLabels = data.datasets[tooltipItem.datasetIndex]
.afterLabels[tooltipItem.index];
return (
afterLabels
);
},
},
},
}}
/>
);
}
答案 0 :(得分:0)
我想做同样的事情,但是我找不到方法。因此,这就是我发现的一种解决方法:
获取数据后,您可以更新选项:
this.setState({
doughnutOptions: {
tooltips: {
callbacks: {
label: function () {
let value = response.data.total;
let label = response.data.name;
return value === 0 ? label : label + ': ' + value;
}
}
}
}
});
我的甜甜圈看起来像这样:
<Doughnut data={this.state.myData} min-width={200} width={400}
height={400} options={this.state.doughnutOptions}/>
最初,oughnutOpitions只是状态中定义的一个空对象:
doughnutOptions: {}
这就是没有数据时的样子:
如果您发现了一种更好的不显示数据的方法,请分享。如果没有,我希望解决方法对您足够好!