gpt4 book ai didi

angular - ng2-图表 : How to show percentage values inside the chart?

转载 作者:行者123 更新时间:2023-12-05 06:08:33 25 4
gpt4 key购买 nike

我已经用谷歌搜索了几个小时,但还没有找到答案。我正在使用 ng2-chart 在我的仪表板中生成图表。它运行良好,问题是我想在圆环图中显示百分比值,但我不知道该怎么做。

这是我的代码:

<canvas baseChart [data]="dashboard.graficoDespesaMensal.valorTotalDespesa"
[labels]="dashboard.graficoDespesaMensal.descricaoCategoria" [options]="optionsGraficoDespesa"
[chartType]="'doughnut'">
</canvas>

  optionsGraficoDespesa: ChartOptions = {
responsive: true,
tooltips: {
enabled: true,
callbacks: {
label: function (tooltipItem, data) {
let label = data.labels[tooltipItem.index];
let count: any = data
.datasets[tooltipItem.datasetIndex]
.data[tooltipItem.index];
return label + ": " + new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(count);
},
},
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value * 100 / sum).toFixed(2) + "%";
return percentage;
},
color: '#fff',
}
}
};

结果是:

enter image description here

不幸的是,我在 [options] 输入中使用的插件无法正常工作。我该如何解决这个问题?

最佳答案

我通过执行以下操作解决了这个问题:

npm i chartjs-plugin-datalabels

组件:

import * as pluginDataLabels from 'chartjs-plugin-datalabels';

public chartPlugins = [pluginDataLabels];

optionsGraficoDespesa: ChartOptions = {
responsive: true,
tooltips: {
enabled: true,
callbacks: {
label: function (tooltipItem, data) {
let label = data.labels[tooltipItem.index];
let count: any = data
.datasets[tooltipItem.datasetIndex]
.data[tooltipItem.index];
return label + ": " + new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(count);
},
},
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr: any[] = ctx.chart.data.datasets[0].data;
dataArr.map((data: number) => {
sum += data;
});
let percentage = (value * 100 / sum).toFixed(2) + "%";
return percentage;
},
color: '#fff',
}
}
};

HTML

<canvas baseChart data]="dashboard.graficoDespesaMensal.valorTotalDespesa"
[labels]="dashboard.graficoDespesaMensal.descricaoCategoria" [options]="optionsGraficoDespesa" [plugins]="chartPlugins"[chartType]="'doughnut'">

结果:

enter image description here

关于angular - ng2-图表 : How to show percentage values inside the chart?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65117544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com